0

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 });
}
1
  • What is the error? Commented May 14, 2020 at 6:22

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

0

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 });
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.