6

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}}}
Abdullah Ilgaz
  • 719
  • 1
  • 17
  • 39

2 Answers2

4

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

Kevin Amiranoff
  • 13,440
  • 11
  • 59
  • 90
2

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.

Saeid
  • 1,996
  • 4
  • 27
  • 44
  • good point! And thank you for saying I was completely right ahah – Kevin Amiranoff Sep 19 '18 at 16:23
  • So sorry guys, looks like my question was cut off a bit. I followed Kevin's original answer and I'm trying to output a parameter like name but get "undefined". `this.setState({ profile: responseJSON }, () => { console.log("profile = " + this.state.profile.name); });` – Steven Sheffey Sep 20 '18 at 05:54
  • @StevenSheffey: That is strange, how about my approach? dose it work? – Saeid Sep 20 '18 at 08:31
  • @Reza Strange indeed, I will try your solution tonight and get back to you guys asap. – Steven Sheffey Sep 20 '18 at 21:45