Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React can't set state

Tags:

reactjs

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;
like image 717
Samy Avatar asked May 16 '26 03:05

Samy


1 Answers

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);
}
like image 119
Yury Tarabanko Avatar answered May 18 '26 16:05

Yury Tarabanko