Monoxyd
Monoxyd

Reputation: 486

Getting [object Object] instead of object in React

I'm fetching an array of objects in my React application. Later I am returning a Product component to each object.

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

  useEffect(() => {
    fetch("http://localhost:8080/products")
      .then(resp => resp.json())
      .then(resp => {
        console.log(resp); //line 55
        setProducts(resp)
      })
  }, []);

  return (
      <div>
        {products.map(product => {
          return <Product product={product} />
        })}
      </div>
  );

This is result of my console.log(resp) in line 55:

    Array(6) [ {…}, {…}, {…}, {…}, {…}, {…} ]
​
0: Object { id: 1, name: "prod 3", amount: 30, … }
​​
active: true
​​
amount: 30
​​
id: 1
​​
name: "prod 3"
​​
<prototype>: Object { … }
​
1: Object { id: 23, name: "prod 2", amount: 20, … }
​
2: Object { id: 4, name: "Angular course", amount: 19, … }
​
3: Object { id: 42, name: "peanut butter", amount: 13, … }
​
4: Object { id: 43, name: "soup", amount: 12, … }
​
5: Object { id: 15, name: "hot-dog", amount: 11, … }
​

​
length: 6
​
<prototype>: Array []

So I am passing a single object to my Product component. However, when I want to view the passed object in the logs, I get the object inside the object:

 const Product = (product) => {
      console.log(product); // result: Object { product: {…} }
 }

Why am I getting an object inside an object instead of a single object?

Upvotes: 2

Views: 8210

Answers (1)

In react the argument for a component is always their props object. This is an object with all the properties you define in the tag. So, for example if you define <Product anotherProp={anotherProp} product={product} /> you would get a props object with the keys product and anotherProp. So the correct way to get the product is through destructuring assingment.

const Product = (props) => {
      const {product} = props;
      console.log(product); // result: Object { product: {…} }
 }

If you wish that your props object is exactly your product object you have to change the way you set your tag... In your case, it would be something like this...

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

  useEffect(() => {
    fetch("http://localhost:8080/products")
      .then(resp => resp.json())
      .then(resp => {
        console.log(resp); //line 55
        setProducts(resp)
      })
  }, []);

  return (
      <div>
        {products.map(product => {
          return <Product {...product} />
        })}
      </div>
  );

Upvotes: 2

Related Questions