Home > Software engineering >  console.log(object) works, trying to access a property from object returns undefined
console.log(object) works, trying to access a property from object returns undefined

Time:02-21

Here is how the object is set :

const Product = () => {

  const location = useLocation();
  const id = location.pathname.split("/")[2];

  const [product, setProduct] = useState({});

  useEffect(() => {
    const getProduct = async () => {
      try {
        const res = await publicRequest.get("/products/find/" id);
        setProduct(res.data);
      } catch {}
    };
    getProduct()
  }, [id]);

when I console.log(product) I get the object return with all the properties:

product: Object { _id: "812389123981278", title: "Lalalala", description: "desc here", … }
​​
__v: 0
​​
_id: "98123789128793"
​​
categories: Array(3) [ "Protein", "Supplements", "Apparel" ]
​​
createdAt: "2022-02-12T22:46:46.138Z"
​​
description: "desc here"
​​
img: "https://raw.githubusercontent.com/LazarVell/irongrip/main/src/images/optimumnutritionisolate.webp"
​​
inStock: true
​​
price: 50
​​
size: Array [ "L" ]
​​
title: "Optimum Nutrition Gold Standard Isolate"
​​
types: Array [ "Protein" ]
​​
updatedAt: "2022-02-12T22:46:46.138Z"

I am trying to get the properties to pass into my React component.

  return (
        <Container>
          <Navbar/>
          <Wrapper>
            <ImgContainer>
            <Image src={product.img} />
            </ImgContainer>
            <InfoContainer>
              <Title>{product.title}</Title>
              <Description>{product.description}</Description>
              <Price> {product.price}</Price>

I can't extract any of these properties, they always return undefined. What am I doing wrong here? The object itself is fine.

CodePudding user response:

try this

  useEffect(() => {
    const getProduct = async () => {
      try {
        const res = await publicRequest.get("/products/find/" id);
        setProduct(() => res.data);
      } catch {}
    };
    if (!_.isEmpty(id)) { // _ is lodash, npm i lodash
      getProduct()
    }
  }, [id]);

CodePudding user response:

product is just a blank object before you call from the API using useEffect. You render the component while the object has no properties, so it errors when you access nested properties. You could have a loading component that shows while product is still a blank object with no properties, and renders product when it is not a blank object.

if (product === {}) return <Loading/>

return () <- react component code here

You can also make a new state called loading, have it be a boolean, and have it change to true after the component gets the data.

  • Related