Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting undefined when json fetch in react native

In my simplified code below I am able to pull data in JSON format but if I try to console log a specific key of the object, I get undefined.

I had thought I could use this.state.profile.name to display "Steven". Why is this coming up as undefined when I'm able to see the entire response? Thanks!

state = {
responseJSON: null,
};
callGraph = async token => {

const response = await fetch(
  `https://graph.facebook.com/me?access_token=${token}&fields=id,name,email,about,picture`
);
const responseJSON = JSON.stringify(await response.json());

  this.setState({ 
    profile: responseJSON
  });

console.log("profile = " + this.state.profile);
};

this console.log output the following:

profile = {"id":"*******","name":"Steven *******","email":"steve@*******.com","picture":{"data":{"height":50,"is_silhouette":false,"url":"https://platform-lookaside.fbsbx.com/platform/profilepic/?asid=*******&height=50&width=50&ext=1539943832&hash=AeQM2VfUBmdfOVJZ","width":50}}}
like image 824
Steven Sheffey Avatar asked Sep 19 '18 10:09

Steven Sheffey


2 Answers

setState is asynchronous.

In your code, you are trying to console.log before the state is updated.

You need to use the callback as the second argument of the setState function:

 this.setState({ 
    profile: responseJSON
  }, () => {
console.log("profile = " + this.state.profile);

});

Check this post for more information or also this other question

like image 180
Kevin Amiranoff Avatar answered Oct 03 '22 21:10

Kevin Amiranoff


setState is asynchronous. The answer of Kevin is completely right. However, you can also use this method to see the result immediately:

this.profile= responseJSON;
console.log("profile = " + this.profile);

You should also define it in the constructor like this:

  constructor(props) {
    super(props);
    this.profile='';
   }

Also, in order to access the parameter of profile in your screen you need to use this.profile.

like image 45
Reza Avatar answered Oct 03 '22 23:10

Reza