简体   繁体   中英

React Native Fetch Function Clearing State

everyone I am brand new to React Native and trying something that may be way over my head. I am looking to to use the fetch command to pull in data and save it as a property of my state. Here is my code:

componentDidMount() {
fetch('http://swapi.co/api/people/')
.then(response => response.json())
.then(responseData => {
  this.setState({
    tweets: responseData.results
  });
  console.log(this.state.tweets)
})
.catch(error => {
  alert('Fetching and parsing data error ' + error);
})
.then(console.log(this.state.tweets));

} the first console.log() outputs the correct array I am pulling, but the second console.log() displays null.

Can someone explain why this is happening? Thank you

setState is asynchronous so checking state right after setting it will not work.

To see state after it's set - pass callback to set state as second argument.

this.setState({
    tweets: responseData.results
}, () => console.log(this.state.tweets));

setState calls also render method, so you can preview new state there.

If you tag your console.log something like "first", "second", etc., you will see that your last console.log invokes firstly. So fixed that, you should wrap the last console.log with fat arrow or anonymous function. So it will be invoked in the order you want.

componentDidMount() {
  fetch('http://swapi.co/api/people/')
  .then(response => response.json())
  .then(responseData => {
    this.setState({
      tweets: responseData.results
    });
  console.log(this.state.tweets)
  })
  .catch(error => {
    alert('Fetching and parsing data error ' + error);
    })
  .then(()=>console.log(this.state.tweets)); // Here
}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM