I have an array of products for which I'm using context api to maintain their state and cookies to persist them after refresh. On a click event I want to increase the number of items loaded from the context and store them as updated cookies. The data itself is updated and saved but the UI is not showing its change until a refresh.
const context = useContext(AppContext)
const [cartContext, setCartContext] = useState([]);
const [currentImage, setCurrentImage] = useState()
const [currentQuantity, setCurrentQuantity] = useState(false)
const [cartCookie, setCartCookie] = useState([]);
useEffect(()=>{
if(currentImage != undefined) {
context.cart[currentImage].quantity += 1
Cookie.set("cartCookie", JSON.stringify(cartCookie));
}
}, [currentQuantity])
useEffect(() => {
setCartCookie(context.cart)
}, [context.cart]);
function findImg(img) {
const findImg = cartContext.findIndex((item, index) => item.name == img.name)
return findImg
}
useEffect(() => {
setCartContext(context.cart)
}, [context.cart, cartContext])
return(
{cartContext.map((image) => (
<div>
<Row>
<Col>
<img src={image.img} alt="" />
<div>
<p>
<strong>{image.category}</strong> <br/> {image.name}
</p>
</div>
</Col>
<Col>
<div className={styles.cartColBox}>
{image.price}
</div>
</Col>
<Col>
<div>
<div className={styles.cartMiddleBox}>
{image.quantity}
</div>
<div>
<div onClick={() =>
(setCurrentImage(findImg(image)), setCurrentQuantity(!currentQuantity))
}>
+
</div>
<div>
-
</div>
</div>
</div>
</Col>
<Col>
<div>
100
</div>
</Col>
</Row>
</div>
))}
)
I had to use spread operators for the array states. The issue was that by default JavaScript doesn't recognize the change if a value changes within the array. Also explained here: https://github.com/vercel/next.js/discussions/32802
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With