Home > Software design >  Cannot read property 'push' of undefined in empty array
Cannot read property 'push' of undefined in empty array

Time:10-26

Trying to get rid of the error TypeError: Cannot read property 'push' of undefined. I have this snippet causing the issue:

const parent_lead_contact = this.props.parentLeads?.filter((lead) =>
      lead.contact_guid.includes(this.props.parent_lead_party_guid)
    );// This is an array which can be empty
    if (parent_lead_contact?.length > 0) {
      parent_lead_contact[0].is_parent_lead_contact = true;
    } else {
      parent_lead_contact.push({ is_parent_lead_contact: true }); //  TypeError: Cannot read property 'push' of undefined
    }

Is there a proper way to get this? I am filtering data from a selector. Sometimes, the result would be an empty array. The important thing is that the selector is not returning is_parent_lead_contact property, but I have to add this property to the array regardless the array is empty.

Thanks a lot for spotting the issue.

CodePudding user response:

If an optional chain fails, everything past the ?. is ignored, and the expression evaluates to undefined. So this line

const parent_lead_contact = this.props.parentLeads?.filter((lead) =>
      lead.contact_guid.includes(this.props.parent_lead_party_guid)
);// This is an array which can be empty

will not produce an array that might be empty - rather, it'll produce either an array that's been filtered, or undefined. That line should be changed to

const parent_lead_contact = this.props.parentLeads?.filter((lead) =>
      lead.contact_guid.includes(this.props.parent_lead_party_guid)
) ?? [];
  • Related