Home > Software engineering >  Cannot read properties of undefined (reading 'includes') in React JS
Cannot read properties of undefined (reading 'includes') in React JS

Time:05-27

These are my error coding, propApptData.doctor values are Dr X|Dr Y. I want to split the propApptData.doctor values and then put them in the resource, after that I reload the webpage and go to trigger this function, the page cannot show anything.

if (propApptData !== undefined && preDoctor !== true) {
      const doctors = propApptData.doctor.includes("|") ? propApptData.doctor.split("|"): propApptData.doctor;
      setDoctorDetailList([...doctorDetailList, { resource: doctors }]);
      setPreDoctor(true)
    }  

In the other function If the value just does not include |, just 1 doctor name, the function can be work if using below coding:

propDoctorName value is Dr.X

if (propDoctorName !== undefined && preDoctor !== true) {
      setDoctorDetailList([...doctorDetailList, { resource: propDoctorName }]);
      setPreDoctor(true)
    }

The error result is shown below:

img1

Hope someone can guide me on how to solve this problem. Thanks.

[Update - 1 ]

What I have tried just now, the doctor list cannot split into array like below picture:

if (propApptData !== undefined && preDoctor !== true) {
      const doctors = propApptData.doctor ? propApptData.doctor.split("|"): [propApptData.doctor];
      setDoctorDetailList([...doctorDetailList, { resource: doctors }]);
      setPreDoctor(true)
    }  

enter image description here

[Updated -2]

img3

[Updated -3]

img5

CodePudding user response:

propApptData.doctor is undefined to solve it you can add ? mark like thispropApptData.doctor?.includes("|")

CodePudding user response:

The error self-explanatory, propApptData.doctor is undefined. To void these kinds of errors in the future, you can use the optional operator or assign a default value using the nullish operator or logical OR operator.

// Optional operator
const doctors = propApptData.doctor?.includes("|") ? propApptData.doctor.split("|"): propApptData.doctor;

// Nullish Operator
const doctors = (propApptData.doctor ?? "" ).includes("|") ? propApptData.doctor?.split("|"): propApptData.doctor;

// Logical Or
const doctors = (propApptData.doctor || "" ).includes("|") ? propApptData.doctor?.split("|"): propApptData.doctor;

You can read more from here.

  • Related