stackato
stackato

Reputation: 1145

Javascript - await fetch response

I have a React-Native app and when the component mounts, I want to fetch data by calling a method in our services class, wait for that data to be returned, then set that data in setState({}). But setState({}) is called before the data is returned.

//Component class

componentDidMount(){
   this.getData();
}

async getData() {
    const data = await MyService.getData();
    this.setState({
        blah:data //undefined
    });
}

//Services Class

let MyService = {
    getData:function(){
        axios.get(url)

    .then(response => response.data)
    .then((data) => {
            //do stuff
          return data;//need to set this to state back in component class
     })
     .catch(error => {
            console.log(error);
     });   
      }
}

module.exports = MyService;

Upvotes: 1

Views: 83

Answers (1)

andsilver
andsilver

Reputation: 5992

You have to return the axios.get call. Otherwise the async function will return an empty promise (promise with the undefined value).

let MyService = {
  getData: function() {
    return axios.get(url)
      .then(response => response.data)
      .then((data) => {
        // do stuff
        return data; // need to set this to state back in component class
      })
      .catch(error => {
        console.log(error);
      });   
  }
}

If you return this axios call, it's itself a promise and you're not waiting until it resolves, so there's no need to use async.

Upvotes: 1

Related Questions