Skip to content
Advertisement

Updating state inside child and using updated value in parent

I am trying to create a really basic header mini cart with cart item counter in NextJS. Im using the form state value in the header component and then using that value in the child components of the header where the numerical value is rendered.

Currently I have the total item count show correctly when I submit my form and I can see the correct value of items showing in the header counter and the mini cart item as expected.

However, when I click to remove the item in the mini cart I would like to reset the entire counter state back to 0 from whatever its previous value was and re-render the header and mini cart/cart item components so that the product item is hidden in the mini cart again.

Here is a basic run through of current components.

product-form.js

JavaScript

header.js

JavaScript

mini-cart.js

JavaScript

mini-cart-item.js

JavaScript

UPDATE 07/09/2022:

I have fixed this issue. Issue was resolved by passing setCartCountState as a value into all of the nested children components. This then allowed me to create a click event in the mini-cart-item.js component that would allow me to use the following function to reset the counter back to 0 and hide the mini cart items.

JavaScript

Answer can be demoed here: https://stackblitz.com/edit/nextjs-lzqu46?file=components/cartitem.js

Advertisement

Answer

Where does the count of HeaderRight come from? All the rendering logic comes from this value. If this is a state, pass down also its set function to CartItem. Then you can do the following with the button:

JavaScript

The CartItem component would look like:

JavaScript
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement