D
D
DeniSidorenko2020-11-02 07:09:55
React
DeniSidorenko, 2020-11-02 07:09:55

Why is 1 element of Stat empty?

Hello, I have the following code

const [item, setItem] = useState({
    id: null, name: "", price: "", weight: ""
  })
  const [cart, setCart] = useState([])


  const addToCart = (id, name, price, weight) => {
    setItem({item, id:id, name:name, price:price, weight:weight})
    setCart(cart => [...cart, item])
  }

When I click on a product, I add it to the cart, and display the cart itself using the map method in the sidebar. There is a problem that when you click on a product in cart 1 of the elements, an item appears with Default values ​​\u200b\u200bthat I set for the InitialState item

Answer the question

In order to leave comments, you need to log in

2 answer(s)
P
Pavel Shvedov, 2020-11-02
@DeniSidorenko

For setCart, you need to use useEffect with an item dependency, since adding to the cart is essentially a side effect of setting a new item, in this case

R
real2210, 2020-11-02
@real2210

Updating states in react asynchronously happens

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question