Michael L
Michael L

Reputation: 39

Having trouble with Async/Await Fetching from an API in React

Using React for this first time.
I'm trying to fetch from an api, but it keeps showing up as undefined.
I curl it on my command line and the data is received.

async componentDidMount() {
        const url = "https://covidtracking.com/api/v1/states/current.json";
        const { data } = await fetch(url);

        const modifiedData = data.map( (stateData) => ({
            state: stateData.state,
            pos: stateData.positive,
        }))

        this.setState({ data: modifiedData, loading: false });
}

Upvotes: 0

Views: 50

Answers (2)

deerawan
deerawan

Reputation: 8443

If you want to avoid promise and use pure async/await this can be alternative

async componentDidMount() {
  const url = "https://covidtracking.com/api/v1/states/current.json";

  const response = await fetch(url);
  const data = await response.json(); // call json() with await

  const modifiedData = data.map((stateData) => ({
    state: stateData.state,
    pos: stateData.positive,
  }));

  this.setState({ data: modifiedData, loading: false });
}

Upvotes: 0

John Velasquez
John Velasquez

Reputation: 3451

You have to call json() to get the json form of your data

async componentDidMount() {
        const url = "https://covidtracking.com/api/v1/states/current.json";
        const data = await fetch(url).then((res) => res.json());

        const modifiedData = data.map((stateData) => ({
            state: stateData.state,
            pos: stateData.positive,
        }))

        this.setState({ data: modifiedData, loading: false });
}

Reference: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

Upvotes: 1

Related Questions