In nextJs I created a provider for useState
, now I am able to add items to the cart, but that’s all that I can do…
cart = [{product: "product name", count:1}]
When I want to add an item to this I can do
setCart([...cart, {product:'new one', count:1}])
But I am just not able to write code that will update the count of existing items in the cart…
I don’t know how…
3
Answers
You cannot just spread the new item. You need to check the existing cart and update according.
In the React demo below, you can click the buttons to add the items to the cart.
Because React uses
Object.is
to compare equality we need to ensure that the new object we pass tosetState
has a different reference.I’d do this with a little custom hook. It could look something like so:
The idea being that if you’re using arrays in your
useState
a lot it might make sense to have a few helper functions ready to go.You could then add some other utility functions (like delete, pop, etc).
You’re probably better off using useReducer vs. useState, due to the complexity of your model. Try something like this:
However, useState has a form that lets you get at the old version of the state if you want to do it that way.