0

I keep getting this error while I have tried everything according to my knowledge any kind of help will be appreciated.

I try to pass the array in props then get in component and set props value in the state but when I try to map that array this error shows up:

TypeError: Cannot read property 'map' of undefined

onClick function:

const handleClickOpen = (data) => {
  setOpen(true);
  setPropsData(data);
};

Event handler:

onClick={() => {
  handleClickOpen({
    name: item.firstName,
    image: item.image,
    about: item.about,
    id: item._id,
    interests: item.intersets,
  });
}}

Component passing props:

<ProfileDialog
  selectedValue={propsData}
  open={open}
  onClose={handleClose}
/>

Component declares props like so:

const { onClose, selectedValue, interests, open } = props;

I got the error when I put in this statement:

<div>{selectedValue.interests.map((item,i) => console.log(item,i))}</div>
3
  • Try this <div>{selectedValue?.interests.map((item,i) => console.log(item,i))}</div> Commented Aug 7, 2021 at 11:17
  • I can't tell much with that much code example. You might want to verify if selectedValue.interests is an array. Try logging them first. Commented Aug 7, 2021 at 11:17
  • wait I just try but I don't know how to share code on the sandbox. Commented Aug 7, 2021 at 11:18

1 Answer 1

2

Until you set the value interests are undefined. do null check before access.

selectedValue?.interests?.map

It is recommended to do null check before accessing nested objects, Optional chaining will help us in this regard.

Sign up to request clarification or add additional context in comments.

1 Comment

Might be worth pointing out/adding documentation for optional chaining so your answer is more clear.

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.