1

I've been looking for a while on Stack but I cannot work out a solution.

I have one method that invoked should do a GET request with Axios.

At the beginning of the method I created a new hash , so I want to store all information there and then just return that hash.

import React, {Component} from "react";
import axios from 'axios';
class Json extends Component{
  getInformation(){
    let inf = {};
     axios
      .get("http://codepen.io/jobs.json")
      .then(result=> {
        inf.description = result.data.jobs[0].description;

      })
      .catch(err=>{
        console.log("STH WRONG");
      });

      console.log(inf);
    return(inf);
  }

So what's my problem???? If I check what is inside the inf variable, it's empty. However, if I inspect with Chrome, on console I see it empty but when i check with detail the key and value are there. At the moment that i am trying to retrieve the information with inf.description is undefined.

Any idea?? Feel free to try this example, just invoke this method to check it.

EDIT

import React, {Component} from 'react';
import axios from 'axios';
class Json extends Component{
  constructor(props){
    super(props);
    this.state={title: ""};

  }
  getInformation(){
    let inf = {};

    // .get("/data/CA_data.json")
     axios
      .get("http://codepen.io/jobs.json")
      .then(result=> {
        inf.description = result.data.jobs[0].description;

      })
      .catch(err=>{
        console.log("STH WRONG");
      });

      console.log(inf);
    return(inf);
  }

  render(){
    let inf = this.getInformation();

    return(
      <h1>

      </h1>
    );
  }
}


export default Json;
Pineda
  • 7,435
  • 3
  • 30
  • 45
Ruffeng
  • 537
  • 7
  • 23
  • read this http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call – azium Nov 18 '16 at 22:24
  • I'll check it well when i'll be on the laptop! It looks really interesting and useful – Ruffeng Nov 18 '16 at 22:29
  • @azium Man really thanks for this link. I had some issues there and thanks to this i fixed! – Ruffeng Nov 21 '16 at 15:50

1 Answers1

1

When you make a get request with axios, you are invoking something that creates a Promise object which represents the status of the async request made. This could be a failed response, a resolved (successful) response, or pending.

The reason you are having issues obtaining the correct state are then you have logged the data immediately after you have invoked your get call and at this point, inf.description is not what you expected it to be but is most likely the Promise object with status 'pending'.

Here is a proposed solution for you:

import React, {Component} from "react";
import axios from 'axios';
class Json extends Component{
  constructor(props){
    super(props);
    this.state = { inf: {} }
  }
  componentDidMount(){
    this.getInformation();  // make the axios call in this lifecycle method
  }
  getInformation(){
    return axios
      .get("http://codepen.io/jobs.json")
      .then(result=> {
        this.setState({ inf.description: result.data.jobs[0].description });
        // this.state.inf.description is available here because
        // then() gets called once the promise has been resolved

        // the call to this.setState causes a re-render of this component
      })
      .catch(err=>{
        console.log("STH WRONG");
      });
  }
  render(){
    // this header will initially show the initial value of description
    // once the PROMISE from the getInformation call within 
    // componentDidMount resolves and calls this.setState, 
    // this component will re-render with the updated state value(s)

    <div>{ this.state.inf.description }</div>
  }
}
Pineda
  • 7,435
  • 3
  • 30
  • 45
  • console.log is just to test. I want to store the information inside inf hash. What i want to return is the hash inf – Ruffeng Nov 18 '16 at 17:29
  • I see, what you can do is save it on state, I've amended my answer accordingly – Pineda Nov 18 '16 at 17:35
  • i've tried as well. And i don't know why but i'm entering on a loop of undefined!!!! Really weird – Ruffeng Nov 18 '16 at 17:40
  • I'm not on the computer but the rest is just the render and a variable invoking this method... – Ruffeng Nov 18 '16 at 17:43
  • :) knowing the specifics would allow me to provide a more specific and useful answer, what I've provided so far should solve your issue of not being able to assign the response to a components state. – Pineda Nov 18 '16 at 17:48
  • I edit the problem. So here it is all my code for this test – Ruffeng Nov 18 '16 at 18:50
  • 2
    @Ruffeng You're still assuming the request is synchronous, which it isn't. You return from `getInformation` before the request has completed. – Dave Newton Nov 18 '16 at 18:54
  • @DaveNewton i can understand you but i am not sure how to fix it. Could you purpose me a solution? – Ruffeng Nov 18 '16 at 20:51
  • @DaveNewton you could put your axios call within the componentDidMount lifecycle call, I'll update my answer to represent this – Pineda Nov 18 '16 at 22:00
  • @Pineda i'll try it! Really thank you for your help – Ruffeng Nov 18 '16 at 22:26
  • @Pineda. It works! Really thanks for your help. I wasn't doing async, so for this reason was all time in blank. Now I can understand well. Really appreciate your help!!! – Ruffeng Nov 21 '16 at 15:49
  • Excellent! I'd very much appreciate marking as accepted if you feel my answer is deserving of it. Either way: Glad I could help :). – Pineda Nov 21 '16 at 16:56