skip to Main Content

Here is my code:

const Category = (categories) => {
  return (
    <div className="shop-by-category">
      <div className="categories">
        {categories.data.map((item) => (
          <div key={item.id} className="category">
            <img src={process.env.REACT_APP_STRIPE_APP_DEV_URL + item.attributes.img.data.attributes.url} alt="" />
          </div>
        ))}
      </div>
    </div>
  );  
};

And here is the error I get:

TypeError: Cannot read properties of undefined (reading ‘map’)

I’ve checked out every possible thing, but still not working.

2

Answers


  1. The categories object you’re passing to the component doesn’t have a data field. You can add a guard clause to render the component:

    const Category = (categories) => {
      if (!categories || !categories.data) {
        return <>No Data</>;
      }
      return categories.data.map((item) => (
        <img
          src={
            process.env.REACT_APP_STRIPE_APP_DEV_URL +
            item.attributes.img.data.attributes.url
          }
          alt=""
        />
      ));
    };
    
    
    Login or Signup to reply.
  2. This error is simply telling you that the attribute ‘data’ does not exist on ‘categories’. If you’re fetching the categories from some external APIs , this is mostly because the database is still empty, so there are no categories yet. However, if you still want to render your component, you can easily check the attributes by adding a ‘?’ if you’re not sure if they exist or not.

     const Category = (categories) => {
      return categories?.data?.map((item) => (
        <img
          src={
            process.env.REACT_APP_STRIPE_APP_DEV_URL +
            item.attributes.img.data.attributes.url
          }
          alt=""
        />
      ));
    };
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search