Reputation: 1
I am having a problem rendering the props value in react.
I have added data fetched from an API to a redux store, and then mapped the state to my App component. The data shows up in my props when I view the component using react dev tools, and I can access the value of the API prop through the console by typing:
$r.props.products.items[0].title
Here's an image of Chrome dev tools illustrating ability to access props from App component for reference:
But when I try to render the props in the App component using
{this.props.products.items[0].title}
The component breaks and I receive an error in the console saying:
Uncaught TypeError: Cannot read property 'title' of undefined
If it helps, I've created a gist here showing my App.js component where the state is mapped to the props, the actions and reducers for the redux store.
If anyone can help me that would be great. I've been pulling my hair out over it all day.
Upvotes: 0
Views: 1353
Reputation: 2603
If the previous answer is not working, the only thing I can think of is that items may exist as an empty array, in the form of this.props.products.items = []
Try:
{
this.props.products.items &&
this.props.products.items.length > 0 &&
this.props.products.items[0].title
}
Upvotes: 0
Reputation: 104369
Reason is, you are fetching the data from api, until you didn't get the response {this.props.products.item}
will be undefined, because render
will get executed before you get the response. So either you need to hold the rendering by using some bool until you didn't get the response or put the check, like this:
{this.props.products.items && this.props.products.items[0].title}
Upvotes: 2