0

Probably I'm doing something wrong, I'm very new in react. So, I just need to get the value of a property of the product object.

function Products() {

    const [products, setProducts] = useState([]);


    useEffect(() => {
        api.get('/product/list')
            .then(response => {
                setProducts((response.data))
            })
    }, [])


    return (
            <div className="main">
                  <div id="landings">
                   {console.log(products)}
                </div>
            </div>
    );
}

export default Products;

When I use the console.log(products[0]), I got this:

Console

But, if I try to get a property of the object, like that: console.log(products[0].name)

I got the error

TypeError: Cannot read property 'name' of undefined

What am I doing wrong?

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
  • Probably a combination of [how-do-i-return-the-response-from-an-asynchronous-call](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) and [is-chromes-javascript-console-lazy-about-evaluating](https://stackoverflow.com/questions/4057440/is-chromes-javascript-console-lazy-about-evaluating-arrays) – ASDFGerte Nov 06 '20 at 16:26
  • Please provide log output as text, not as a link to a picture of text. You can also do yourself a favor and use `console.log(JSON.stringify(products, null, 2))` to get a printout of the object at the time of evaluation. – Heretic Monkey Nov 06 '20 at 16:41
  • Does this answer your question? [Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference](https://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron) – Heretic Monkey Nov 06 '20 at 16:47

2 Answers2

0

Firstly you need to understand how the React Hooks works.

The reason for this behavior is when this component is mounted, products is initialized with the value [] since you used useState React Hook, and then rendering happens.

Till that time

  • The Value of products is []
  • The value of products[0] is undefined.

That's the reason why console.log(products[0].name) says "Cannot read property 'name' of undefined"

Once the 1st render completes the useEffect hook comes into the picture since it is serving the behavior of componentDidMount here and performs the API call to get products data and assign it to products once response comes.

You should always ensure that you are not trying to access key from the undefined objects

Here, instead of using console.log(products[0].name) use {products && products[0] && console.log(products[0].name)}

this will keep your code from breaking.

For a better understanding of how React Hooks works read this: https://reactjs.org/docs/hooks-overview.html and since you are very new to React understand the lifecycle of React from here https://reactjs.org/docs/state-and-lifecycle.html

Hope you get the idea.. Happy Coding!!!!

0

Initially you get empty array, once fetch the data you receive non empty array so you could simply hide this errors by

return (
  <div className="main">
    {products.length && <div id="landings">{console.log(products)}</div>}
  </div>
);

or

return (
  <div className="main">
    <div id="landings">
      {products.map((product) => (
        <span key={product.id}>{product.name}</span>
      ))}
    </div>
  </div>
);
Lashan Fernando
  • 1,187
  • 1
  • 7
  • 21