-1

I am using axios to retrieve data from my BackEnd but the promise is still pending.

I have used .then() even async and await. I am using .then(res => res.data) since i know that every promise has "data" key holding the retrieved data and that after that it will be returned this way. I also binded the function in the constructor!

async getTrackInfo() {
  return await axios.get('http://localhost:60231/api/values')
    .then(res => res.data);
};


componentDidMount() {
  const data = this.getTrackInfo();
  console.log(data);

  this.setState({
    tracks: data
  });
}

But unfortunately, it returns undefined.

Eddie
  • 26,593
  • 6
  • 36
  • 58
Edwardcho Vaklinov
  • 118
  • 1
  • 1
  • 11
  • 3
    You need `const data = await this.getTrackInfo();` –  Apr 23 '19 at 16:06
  • 1
    `async` functions always return a promise. Promises are a standard way to manage asynchronous operations. `async`/`await` gives you procedural style syntax to manage them with. They don't stop asynchronous operations from being asynchronous – Quentin Apr 23 '19 at 16:06
  • @ChrisG - That will error. `componentDidMount` isn't `async` – Quentin Apr 23 '19 at 16:07
  • 1
    @Quentin pretty sure the instruction to change `componentDidMount()` to `async` was implicit in Chris's comment... – Patrick Roberts Apr 23 '19 at 16:11

1 Answers1

-1

Following code would work:-

async getTrackInfo() {
  return await axios.get('http://localhost:60231/api/values')
    .then(res => res.data);
};


async componentDidMount() { // Make this function async
  const data = await this.getTrackInfo(); // add await here
  console.log(data);

  this.setState({
    tracks: data
  });
}
Sumit Parakh
  • 1,098
  • 9
  • 19
  • 1
    To use `await`, you have to make the function (in this case, `componentDidMount`) `async`. – GregL Apr 23 '19 at 16:07
  • 1
    A small nitpick, the `await` in `return await` is superfluous. Might as well remove `async` from `getTrackInfo()` and `return axios...`. It will do the same thing. – Patrick Roberts Apr 23 '19 at 16:14