Search code examples
reactjstypeerrorreact-component

when myItems is an empty array, it is saying 'myItem.map() is not a function'. how to solve?


When items are present in myItems state, the website is ok. but if there is no item, the website breaks.

const [myItems, setMyItems] = useState([]);

return (
<div className="container my-5">
  <div className="row g-5">
    {
      myItems?.map(myItem => <MySingleItem key={myItem._id} myItem={myItem} handleItemDelete={handleItemDelete} />)
    }
  </div>
</div>
);

Solution

  • The issue is your myItems is actually receiving a value that is not an array type.

    Doing

    const myItems = 'b';
    myItems.map((a) => a)
    

    will give the same error Uncaught TypeError: myItems.map is not a function.

    It's telling you .map is not a function because the data type of the value of myItems at that point in time is something else.

    Check your usage of setMyItems in the rest of your component code or share the full code because I believe you're setting it as a non-array type by mistake.