hania
hania

Reputation: 43

array is not mapping in react js

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>

Upvotes: 0

Views: 105

Answers (1)

Amruth
Amruth

Reputation: 5912

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.

Upvotes: 2

Related Questions