Issue
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?
Solution
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.
Answered By - Paweł Mikołajczuk
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.