Home > front end >  Uncaught TypeError: Cannot read properties of undefined (reading 'companyName') JS Objects
Uncaught TypeError: Cannot read properties of undefined (reading 'companyName') JS Objects

Time:04-22

i have a problem about when i trying mapping my data. I want a reach company name in supplier in products. How can i fix it?

{products.map((repo) => (
      <div
        style={{
          backgroundColor: "#c1d3d4",
          marginTop: 50,
          display: "flex",
          flexDirection: "column",
          minWidth: 1000,
          paddingLeft: 50,
          marginLeft: 400,
          paddingRight: 30,
          paddingBottom: 12,
          borderRadius: 15,
        }}
        span={24}
      >
        <p style={{ flex: 1, fontWeight: "bold", fontSize: 26 }}>
          {repo.name}
        </p>

        <p style={{ fontWeight: "bold", fontSize: 14 }}>{repo.supplier.companyName}</p>

        <p style={{ fontWeight: "bold", fontSize: 14 }}>
          {repo.quantityPerUnit}
        </p>
        <div
          style={{
            display: "flex",
            flexDirection: "row",
            justifyContent: "space-between",
            alignContent: "flex-end",
          }}
        >
          <p
            style={{
              fontSize: 20,
              fontWeight: "800",
              color: "green",
              alignSelf: "flex-end",
            }}
          >
            {repo.unitPrice.toFixed(2)}
          </p>
          <Button type="primary" onClick={() => AddCart(repo)}>
            Sepete Ekle
          </Button>
        </div>
      </div>
    ))}

this is error message error

this is data:

https://northwind.vercel.app/api/products

edit:

@Tim Roberts found the solution. Only some elements have a supplier so other one's dont have. i took the error message when i try map. I understand now.

CodePudding user response:

I think the error occurs because in some data from the api, the supplier prop doesn't exist.

Your code "<p style={{ fontWeight: "bold", fontSize: 14 }}>{repo.supplier.companyName}

"

Possible Solution

"<p style={{ fontWeight: "bold", fontSize: 14 }}>{repo.supplier && repo.supplier.companyName}

"

  • Related