pmdownie
pmdownie

Reputation: 1

React Redux: Can view props in browser console, but return undefined when rendered

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:

Chrome dev tools illustrating ability to access props from App component

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

Answers (2)

Yuan-Hao Chiang
Yuan-Hao Chiang

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

Mayank Shukla
Mayank Shukla

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

Related Questions