0

When the component mounts, I'm making an ajax request that returns an Object with an array of objects.

getPages() {
  getAllPagesData().then((pages) => {
    let data = pages
    this.setState({ pages });
  });
}

Inside this function I can access the data effectively.

console.log(pages.pages[0].description)

Prints the correct page description.

In render I'm setting state to a variable to access in my return:

render() {

  const pages = this.state.pages.pages
  console.log(pages)

return (

That console.log in chrome is:

(55) [Object, Object, Object, Object,...

I'm then trying to iterate through the array using map:

return (
  <div>
    <Nav />
     { pages.map((post, index) => (

It breaks the page and the error is: Cannot read property 'map' of undefined at Pages.render

I've tried many different ways to access this object and the array inside of it, but cannot get individual array items to display inside the render function.

0

1 Answer 1

1

Try using this line in the render method

const pages = this.state.pages.pages || [ ]

It is most likely because the render method is called before the ajax request is complete. So the this.state.pages.pages is undefined initially.

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

1 Comment

"It is most likely because the render method is called before the ajax request is complete" - ah, that seems likely... Yup, that worked, thanks!

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.