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}}}
2
  • Also it should be state = { profile: null}. But I don’t think that will solve your issue. Commented Sep 20, 2018 at 8:44
  • Something else must be wrong in your code. Because if your console log git you this output, you should be able to log this.state.profile.name too Commented Sep 20, 2018 at 9:08

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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.

4 Comments

good point! And thank you for saying I was completely right ahah
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); });
@StevenSheffey: That is strange, how about my approach? dose it work?
@Reza Strange indeed, I will try your solution tonight and get back to you guys asap.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.