Morgan Allen Morgan Allen - 21 days ago 9
React JSX Question

Printing the results from fetch() in React

I'm trying to recreate the example used in the docs https://facebook.github.io/react-native/docs/network.html

componentDidMount: function(){
this.createRow();
},

createRow : function(){
var results = fetch('https://facebook.github.io/react-native/movies.json')
.then((response) => response.json())
.then((responseJson) => {
return responseJson.movies;
});
this.setState({
'xyz' : results,
'people' : [{'name':'something_else', 'email':'email@gmail.com'}, {'name':'morgan', 'email':'mogo@gmail.com'}]

});
},


However, when I goto print the results in the
render
method

render: function(){
console.log(this.state.xyz)


I am getting:
undefined
the first time the page renders (and
xyz
hasn't been set, so that makes sense)

Promise { <state>: "pending" }
the second time when page is rendered (
createRow()
is run from
componentDidMount
)

Why am I getting
pending
state and not the
movies
object like the example shows?

Answer

the case is, when the setState is executed (because your fetch is async, but the flow goes async with fetch method), your promise is not resolved or rejected yet, because the promise is in the pending state. so, you need to call setState after the promise is resolve. can you try this :

createRow : function(){
        fetch('https://facebook.github.io/react-native/movies.json')
            .then((response) => response.json())
            .then((responseJson) => {
               this.setState({
                 'xyz' : responseJson.movies,
                 'people' : [{'name':'something_else', 'email':'email@gmail.com'}, {'name':'morgan', 'email':'mogo@gmail.com'}]

               });
            });
    },