2

This is my json from my Drupal site:

[
    {
        title: "I believe every human has a finite number of heartbeats. I don't intend to waste any of mine.",
        uid: "gestor"
    },
    {
        title: "Man must explore, and this is exploration at its greatest",
        uid: "gestor"
    }
]

It has two elements separate by brackets {} And this is how I am trying to use Fetch in my react component.

componentWillMount(){
    // Con fetch me conecto al site de Drupal
    fetch('http://rest.dd:8080/all-of-us')
    .then(response => response.json())
    .then(postPrvSrv => {
      // A cada post lo coloco en un array
      console.log(postPrvSrv.results)
      postPrvSrv.results.forEach(post => {
        let data = {
          title:post.title,
          author:post.uid
        }
        console.log(data);
        // Actualizamos el state para poder renderizar
        this.setState({postPrvSrv:this.state.postPrvSrv.concat([data])})
      })
    })
  }

This are my console log results:

console.log(postPrvSrv.results) = undefined

console.log(data); = Nothing, cuz it broke on line 27.. in the forEach

console.log(this.state.postPrvSrv.length) = 0. obiusly.

This is the error message:

Unhandled Rejection (TypeError): Cannot read property 'forEach' of undefined

And the error from the console:

Uncaught (in promise) TypeError: Cannot read property 'forEach' of undefined

1 Answer 1

2

If you're directly returning an array from your Durpal endpoint, then the postPrvSrv variable (in your fetch response handler) will be a plain array.

Assuming postPrvSrv is an array, then the .results field on postPrvSrv will be undefined.

This is the reason you will be getting the "Cannot read property 'forEach' of undefined" error - you're trying to call .forEach(..) on the .results field, which is undefined on the postPrvSrv array.

To resolve this issue, try adjusting your code as shown in the comments below:

fetch('http://rest.dd:8080/all-of-us')
.then(postPrvSrv => {

  console.log(postPrvSrv) // Fix this line to see log of data in console

  postPrvSrv.forEach(post => {  // Fix this line
    let data = {
      title:post.title,
      author:post.uid
    }
    console.log(data);

    this.setState({postPrvSrv:this.state.postPrvSrv.concat([data])})
  })

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

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.