Skip to content

Need to extract name value from json array of the output

I am unable to extract the name variable from the graph output of the following react code. trying to store the name value from the json output received from the api in my state variable in React. How do i do it?

state = {
        auth: false,
        username: '',
        access_token: '',
        app_name: [],
    };

    responseFacebook = response => {
        {/*console.log(response);*/}
        if(response.status !== 'unknown')
        this.setState({
            auth: true,
            username: response.name,
            access_token: response.accessToken
        });
        graph.setAccessToken(this.state.access_token);
        graph.get("/me/accounts", function(err, res) {
            let response = res;
            console.log(response.data[0]);
          });
        console.log(this.state);
    }

Answer

Maybe because your checking the second console.log outside the callback. In javascript the callbacks( the function inside the get call ) are trigerred later, when the API completes, hence you will not get anything in the console.log outside the callback, if you rewrite your example it might work.

state = {
    auth: false,
    username: '',
    access_token: '',
    app_name: [],
};

responseFacebook = response => {
    if(response.status !== 'unknown') {
        this.setState({
            auth: true,
            username: response.name,
            access_token: response.accessToken
        });
        graph.setAccessToken(this.state.access_token);
        graph.get("/me/accounts", (err, res) => {
            let response = res;
            this.setState({username:response.data[0]});
            console.log(this.state);
        });
    }
}

Event loop reference