Flama
Flama

Reputation: 868

trying to use fetch in componentDidMount shows undefined [react native]

Here's my componentDidMount:

componentDidMount(){
    return fetch(API_URL + "/[email protected]").then(
      (response) => response.json()
    ).then( (responseJson) => {
      console.log("response is " + responseJson.category)
    }).catch((error) => console.log(error))
}

However the console.log that you see there prints:

 response is undefined

When I acces my API through that exact same URL I get:

[{"category":"Donante","_id":"123","address":"street 32","email":"[email protected]", "__v":0}]

So why am I unable to get the data in my code?

Upvotes: 0

Views: 73

Answers (2)

therobinkim
therobinkim

Reputation: 2568

Since you're getting an array back as a response, make sure you access an individual element of that array first!

ie, change your console.log to "response is" + responseJson[0].category

Upvotes: 1

rleiva93
rleiva93

Reputation: 246

This might be happening because the promise returned by the fetch function, is not fulfilled yet when you're trying to access the response object.

So, you might want to refactor the code with something like the following:

componentDidMount(){
  const promise = fetch(API_URL + "/[email protected]").then(res => res.json());

  Promise.allSettled([promise]).then(([responseJson]) => {
    // you can access your responseJson here
    console.log(`response is ${responseJson.category}`);
  }
}

The Promise.allSettled function returns a promise, that only resolves until the promises given by param are either fulfilled or rejected. In that way, you're accessing the You can check for more details here.

Upvotes: 0

Related Questions