Andie
Andie

Reputation: 11

React typeerror: Cannot read property of undefined - But I can read other props just fine

I am puzzled by this undefined error. Here is my object that I can console.log from render()

{_id: "59e7ac89d14e6d644588eaff", title: "500 thread count sateen sheet set", id: "1233", description: "Sink into dreamland with a luxe sheet set in smoot…at and fitted sheets, along with two pillowcases.", type: "Duvet", …}
addedDate
:
"2017-10-18T19:33:29.468Z"
collectiontype
:
"String"
description
:
"Sink into dreamland with a luxe sheet set in smooth, lustrous organic-cotton sateen that includes flat and fitted sheets, along with two pillowcases."
holiday
:
""
id
:
"1233"
image1
:
{_id: "59e7ac89d14e6d644588eafd"}
image2
:
{_id: "59e7ac89d14e6d644588eafe"}
options
:
{color: Array(2), size: Array(5)}
price
:
(4) [89, 99, 119, 129]
season
:
"All"
subtype
:
""
tags
:
[""]
title
:
"500 thread count sateen sheet set"
type
:
"Duvet"
__v
:
0
_id
:
"59e7ac89d14e6d644588eaff"
__proto__
:
Object

On the first render the object is, in fact, undefined. I handle this by assigning each property to an empty type. Eg:

const price = this.props.detail.price || []

For some reason, regardless of what I do, I cannot access the props of the options obj: color and size. Even this causes the typeError:

const color = this.props.detail.options.color || []

I have no issue accessing and rendering all other props except options.color and options.size. Any ideas?

Upvotes: 1

Views: 558

Answers (1)

palsrealm
palsrealm

Reputation: 5243

Your options object is undefined when you do

const color = this.props.detail.options.color || []

Try doing

const color= this.props.detail.options? this.props.detail.options.color || [] :[];

Upvotes: 2

Related Questions