0

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
2
  • The reason the site wouldn't let you post that codepen link without obscuring it is that your whole question (including any necessary code) has to be in your question, not just linked. Two reasons: People shouldn't have to go off-site to help you; and links rot, making the question and its answers useless to people in the future. Please put a minimal reproducible example in the question. More: How do I ask a good question? Please put all necessary code in your question, ideally using Stack Snippets; here's how to do a React one. Commented Nov 3, 2018 at 10:18
  • Side note (because it's probably not the problem, it's just a problem): You're not checking for fetch failure. You're not the only one, they clearly got the API wrong, this is so common I wrote it up in a post on my anemic little blog. Commented Nov 3, 2018 at 10:18

2 Answers 2

2

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

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

Comments

2

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

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.