Reputation: 3
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.
Upvotes: 0
Views: 2334
Reputation: 828
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.
Upvotes: 1