I'm working in React and trying to fill a ImageGrid with data from a API. There is no problem with getting the data but somehow I cant set my state with the responseData
I can show the data while I get the response from the API but I can't set my state...
componentWillMount()
{
this.state = {
content: ''
};
this.loadContent();
}
loadContent()
{
ApiService.getTweets(topic,numberOfElements,offset).then((responseData) => {
console.log("Data is here",responseData); //<---------- HERE
this.setState({
content: responseData
});
})
console.log("Data is not here",this.state.content); //<---------- HERE
}
Here I get the data:
class ApiService {
static getTweets() {
return fetch("https://MyURL", {
method: 'get'
})
.then((resp) => resp.json())
.then(function(data) {
return data;
}).catch(function(error) {
console.log(error);// Error :(
});
}
}
export default ApiService;
You have async issue: both fetch
and setState
are async.
loadContent() {
ApiService.getTweets(topic,numberOfElements,offset).then((responseData) => {
console.log("Data is here",responseData); //<---------- HERE
this.setState({
content: responseData
}, () => {
// only now the state was updated
console.log("Data is here", this.state.content);
});
// even the nest line runs to early
console.log("Data is not here",this.state.content);
})
// the next line runs to early
console.log("Data is not here",this.state.content);
}
You want to use the set state callback as state is not set instantly.
loadContent() {
ApiService.getTweets(topic,numberOfElements,offset).then((responseData) => {
console.log("Data is here",responseData); //<---------- HERE
this.setState({
content: responseData
}, () => {
console.log("Data is here",this.state.content); //<---------- HERE
);
})
}
You need to implement componentDidUpdate
. Don't rely on the promises to know when your component has updated. React's life-cycle will worry about that after the system has updated. See below.
From that point you can easily do something like
componentDidUpdate(prevProps, prevState) {
if(prevState.content !== this.state.content) {
console.log('I have new content!', this.state.content);
}
}
Also, you can ignore that if statement if you only have one setState()
call in your component. So the short version is as follows:
componentDidUpdate(prevProps, prevState) {
console.log('I have new content!', this.state.content);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.