ptts
ptts

Reputation: 1053

React ajax fetch response undefined

I am using the fetch AJAX example from the docs and am fetching this:

 https://learnwebcode.github.io/json-example/animals-1.json

Here is the componentDidMount part:

componentDidMount() {
fetch("https://learnwebcode.github.io/json-example/animals-1.json")
  .then(res => res.json())
  .then(
    (result) => {
      this.setState({
        isLoaded: true,
        items: result.items
      });
    },

I get "uncaught type error in promise, cannot read property map of undefined"

Why is this happening? This is my first attempt to use the fetch API. I have tried to log the response object, but that returns undefined.

The link to the pen is here:

 https://codepen.io/damPop/pen/yQLbxV

Upvotes: 0

Views: 847

Answers (2)

Matt
Matt

Reputation: 324

result is the array of items hence result.items does not exist:

componentDidMount() {
 fetch("https://learnwebcode.github.io/json-example/animals-1.json")
 .then(res => res.json())
 .then(result => {
     console.log(result)
     this.setState({
       isLoaded: true,
       items: result
     });
   })
 .catch(error => {
   this.setState({
     isLoaded: true,
     error
   });
 })
}

https://codepen.io/mThorning/pen/ZmEyao?editors=0010

Upvotes: 2

Ankush Sharma
Ankush Sharma

Reputation: 677

You are getting error in render method.

Remove items from result.item, because data is in 'result'.

Like below

componentDidMount() {
fetch("https://learnwebcode.github.io/json-example/animals-1.json")
  .then(res => res.json())
  .then(
    (result) => {
      this.setState({
        isLoaded: true,
        items: result // remove items, because data is in 'result'
      });
    },

Upvotes: 2

Related Questions