Caching of cart counter
Unanswered
American Bully posted this in #help-forum
American BullyOP
I am working on a standard ecommerce page that is made with the app router. This means, that I have a small counter inside the header that shows the current number of products inside the cart at any given time. This also means, that whenever the user adds a new item to the cart from a page, we need to update the counter inside of the header to reflect that change. However, I am not sure how to do this in the best way.
First, I tried giving it a cache tag, and then doing revalidateTag whenever a new item was added to the cart. This worked, but it did not only update the counter, but the entire page I was on, refetching all the data from the backend.
Another possible solution could be to put the cart counter inside a global context, and then share that between the different pages and the counter. So, whenever a product is added, we update a state inside the context manually and then read that change into the counter. However, this does not seem like the recommended approch with server components.
This seems like a pretty standard feature for an ecommerce site, so I hope that someone managed to solve it is a good way.
First, I tried giving it a cache tag, and then doing revalidateTag whenever a new item was added to the cart. This worked, but it did not only update the counter, but the entire page I was on, refetching all the data from the backend.
Another possible solution could be to put the cart counter inside a global context, and then share that between the different pages and the counter. So, whenever a product is added, we update a state inside the context manually and then read that change into the counter. However, this does not seem like the recommended approch with server components.
This seems like a pretty standard feature for an ecommerce site, so I hope that someone managed to solve it is a good way.
1 Reply
Sun bear
I would go with your 2nd approach.
Create a useCart() hook that returns all cartItems.
Then in a <Cart /> client side component you can use that hook and show tge count. Maybe also trigger a sheet on click and allow editing the cart.
The useCart() hook can have "addItem", "deleteItem" and then store cart in cookie, local storage or usersccount in database
Create a useCart() hook that returns all cartItems.
Then in a <Cart /> client side component you can use that hook and show tge count. Maybe also trigger a sheet on click and allow editing the cart.
The useCart() hook can have "addItem", "deleteItem" and then store cart in cookie, local storage or usersccount in database