Steven Sheffey
Steven Sheffey

Reputation: 61

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}}}

Upvotes: 6

Views: 1438

Answers (2)

Saeid
Saeid

Reputation: 2046

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.

Upvotes: 2

Kevin Amiranoff
Kevin Amiranoff

Reputation: 14553

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

Upvotes: 4

Related Questions