Jay P.
Jay P.

Reputation: 2590

Keep having the error "TypeError: Cannot read property 'map' of undefined" when using map function in React js

I've been struggling with this, and I don't even know what is wrong there. Here is an explanation for the codes below.

In Slider component, I get storeList from parent component as props, and pass it to RenderSlider.

const Slider = (props) => {
   const { storeList } = props;
   return (
       ....
       <RenderSlider storeList={storeList} />
       ...
   );
}

In RenderSlider, I get storeList from Slider, and then it prints storeList to double check if it has data inside. Like you see the most bottom image, it has 10 stores. However, the error TypeError: Cannot read property 'map' of undefined happens in the code line using map() function. The array has a correct data inside and its type is also printed as object to be array. I tried to debug it with tons of times, but I can't find the reason. Can anyone help me for this?

const RenderSlider = props => {
  console.log(props.storeList);
  console.log(typeof props.storeList);
  return (
    <div>
      {props.storeList.map(store => ( <--- ERROR happens in this line
        <span key={store.id}>{store.businessName}</span>
      ))}
    </div>
  );
};

enter image description here

Upvotes: 1

Views: 440

Answers (3)

Idan
Idan

Reputation: 5450

You need to make sure that there is array before you use map:

In this nice syntax you can just verify that props.storeList is not undefined/null...

const RenderSlider = props => {
  console.log(props.storeList);
  console.log(typeof props.storeList);
  return (
    <div>
      {props.storeList && props.storeList.map(store => ( <--- ERROR happens in this line
        <span key={store.id}>{store.businessName}</span>
      ))}
    </div>
  );
};

Upvotes: 1

Củ Su H&#224;o
Củ Su H&#224;o

Reputation: 390

Seems like your storeList gets data from somewhere and by the time Slider renders, it's not there yet.

Please don't be fooled by Chrome logging, if you click on the [i] icon, you can see the data's just arrived and it logs after rendering.

I think adding your storeList is empty/null before rendering will fix the problem.

Upvotes: 0

Tarek Essam
Tarek Essam

Reputation: 4010

Try this:

const RenderSlider = props => {
  const {storeList} = props;
  if (!storeList) return null;

  if (
  return (
    <div>
       {props.storeList.map(store => (
       <span key={store.id}>{store.businessName}</span>
    ))}
    </div>

); };

Upvotes: 0

Related Questions