user1688401 user1688401 - 1 month ago 10
React JSX Question

Cannot read property 'toJS' of undefined

I have two arrays. But when one of them is null it gives the following error:


Cannot read property 'toJS' of undefined in that line


Here's the relevant call that triggers the error:
{groupsGuney.toJS()}


Here's my declaration of the variables
let groupsGuney, groupsKuzey;


And finally here are my two arrays. But when one of them is null it gives the error:

...
if (muso == 1) {
groupsGuney = this.props.groups
.groupBy((group, idx) => idx % maxRows)
.map((ggs, idx) => {
return this.renderGroups(ggs, idx);
}).toList().flatten(true);
}

if (muso == 2) {
groupsKuzey = this.props.groups
.groupBy((group, idx) => idx % maxRows)
.map((ggs, idx) => {
return this.renderGroups(ggs, idx);
}).toList().flatten(true);
}

var result = (
<div>
<div className={classSelector + ' discard-mini-box-area'} >
{ groupsGuney.toJS() }
</div>
<div className={classSelector + ' discard-mini-box-area'} >
{ groupsKuzey.toJS() }
</div>
</div>
);

return result;
}
}

export default DiscardMiniBoxArea;

Answer

Instead of doing:

<div>
   <div className={classSelector + ' discard-mini-box-area'} >  
     {groupsGuney.toJS()} 
   </div>
   ....

you should do:

<div>
   <div className={classSelector + ' discard-mini-box-area'} >  
     {groupsGuney && groupsGuney.toJS()} 
   </div>
   ....

Before calling a function on your object, you need to make sure it's there. If you're uncertain about your object having the function at all times, you will need an additional check, that makes sure toJS is there and that it's a valid function.

If that's the case, update what's inside your container to:

{groupsGuney && typeof groupsGuney.toJS === 'function' && groupsGuney.toJS()} 

However, ideally, you would not render at all this specific group if what you would like to render is not there. You should move these checks to before you render your component.