Home > Enterprise >  TypeError: Cannot read properties of undefined (reading 'includes') on clicking checkbox
TypeError: Cannot read properties of undefined (reading 'includes') on clicking checkbox

Time:09-15

Link to CodeSandbox code with live project preview

Link to product page where checkbox is present

I've written a piece of code that, when a user goes to the product page and clicks on a checkbox called, "Show Consignment Products Only", it only shows products that have the word "CONSIGNMENT" in the product's name:

// Consignment Only
    if (filters.consignmentOnly &&
      !p.model.includes("CONSIGNMENT")) ||
      ...) {
        return false;
    }

When a user does so at this point, the below TypeScript error comes up:

TypeError: Cannot read properties of undefined (reading 'includes')

It looks like it's saying model is undefined (model refers to the model value in the API data), however I've used model and other values from this API many times and things load fine.

How can I fix this issue?

CodePudding user response:

p.model is not defined. Try:

if (filters.consignmentOnly && (!!p.model && !p.model.includes("CONSIGNMENT"))

The double exclamation lets us check the boolean value of p.model.

!!p.model will return truthy or falsy. If truthy, p.model.includes is cleared to proceed. If falsy, it will end the condition there.

CodePudding user response:

You can try optional chaining:

// Consignment Only
if (filters.consignmentOnly && !p.model?.includes("CONSIGNMENT") || ...) {
    return false;
}
  • Related