0

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.

1
  • 1
    Sometimes, the result would be an empty array ... and sometimes it seems, this.props.parentLeads is undefined - otherwise, why would you use ?.filter rather than just .filter Commented Oct 26, 2022 at 0:45

1 Answer 1

1

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)
) ?? [];
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.