Home > Net >  Cannot read properties of undefined (reading 'name'). thisProduct undefined
Cannot read properties of undefined (reading 'name'). thisProduct undefined

Time:11-16

I have a problem with reading {find}. The problem is in ProductDetail.js. First, click on the products link than on any product to see details. TypeError: Cannot read properties of null (reading 'find') https://codesandbox.io/s/react-router-product-detail-pages-dynamic-links-forked-y1o0n?file=/src/ProductDetail.js:418-429

CodePudding user response:

You've done some mistakes over there in your ProductDetail.js file.

First:

You can use useEffect hook to check and compare if there is a matching id or not.

Second:

You can use useState hook to store the thisProduct and update the thisProduct value by calling setThisProduct and use it in the JSXElement.

This is always a best practice to use the state for data set and get.

Here is more about React.Hooks

Third:

Price is a Object and you can't render your object like that, so use the key instead of object while rendering. like this: {thisProduct?.price?.current?.value}

You can learn more about optional chaining

Fourth:

productId which you're getting from useParams is a string type, and your productId from sneakers is a number type. So you need to change your productId to number while comparing like this: Number(productId)

Learn about Numbers in Js

Here is the complete code of yours:

// ProductDetail.js
import React, { useContext, useEffect, useState } from "react";
import { useParams } from "react-router-dom";
import { StateContext } from "./GlobalContext";

function ProductDetail() {
  const { productId } = useParams();
  const { sneakers } = useContext(StateContext);
  const [thisProduct, setThisProduct] = useState({});

  useEffect(() => {
    if (sneakers) {
      const findProduct = sneakers.find((product) => {
        return product.id === Number(productId);
      });
      console.log("findproduct", findProduct);
      setThisProduct(findProduct);
    }
  }, [productId, sneakers]);

  return (
    <div>
      {thisProduct && (
        <>
          <h1>{thisProduct?.name}</h1>
          <p>Price: {thisProduct?.price?.current?.value}</p>
          <p>{thisProduct?.description}</p>
        </>
      )}
    </div>
  );
}

export default ProductDetail;

CodePudding user response:

completely check your state and props, it is not providing valid data to child component

<StateContext.Provider value={{ sneakers }}>
      {console.log(sneakers, "== thisProduct")}
      {children}
  </StateContext.Provider>

console will show your data, it coming null so that is the issue

  • Related