My code is:
state = { keyItems: [], urlItems: [] }
componentDidMount() {
Storage.list('')
.then(keyItems => {
console.log("keyItems: ", keyItems)
this.setState({ keyItems: keyItems })
/*for each photo key in the folder..*/
keyItems.forEach(function(keyItem) {
/*get the URL*/
Storage.get(keyItem.key)
.then(urlItem => {
console.log("urlItem: ", urlItem)
/*add URL item to state*/
/*ANY CALL TO this.setState HERE DOESN'T WORK, i've tried
even simple tests*/
this.setState(prevState => ({ urlItems:[...prevState.urlItems, { key: keyItem.key, source: urlItem } ]}))
})
.catch(err => {
console.log("error fetching photo URL", err)
})
})
})
.catch(err => {
console.log("error fetching photos keys", err)
})
}
Thanks!
The value of this
is getting lost inside the .then
You could try this
this
to a variablethis
Here it in code
componentDidMount () {
const that = this;
// now call setState like this
that.setState(...)
}
You can read more about it at the link below, but I’ve put the general gist of it here.
this
is always the object the method is called on. However, when passing the method tothen()
, you are not calling it! The method will be stored somewhere and called from there later.
Why is 'this' undefined inside class method when using promises?