Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nextjs component not updating after state change

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> 
    ))}  
   )
like image 258
József Kiss Avatar asked Oct 24 '25 17:10

József Kiss


1 Answers

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

like image 128
József Kiss Avatar answered Oct 27 '25 06:10

József Kiss