I have a content provider for a simple shopping cart in my Next.js 13 app directory. The problem that i’m having is that the addToCart()
function is being called numerous times each time i call the function. This causes issues particularly when i have a item quantity which increments each time addToCart()
is called, thus giving the wrong quantity value.
function addToCart({ id, item_title, item_price, restrict: boolean }) {
console.log("addToCart funtion hit")
updateCart((prev) => {
console.log("updateCart funtion hit")
})
}
The output in inspector reads like this:
addToCart funtion hit
updateCart funtion hit
updateCart funtion hit
If I add reactStrictMode: false
to my next.congif.js config file, the function call is reduced to 1 indicating that is has to do when the component being rendered multiple times. I’ve read that setting reactStrictMode: false
on next.config.js is bad practice, so was attempting to implement that setting for the only the test-cart.js component, but to no avail.
In the root of the directory i have a layout.tsx file which loads the test-cart.js like this:
"use client"
import './globals.css'
import { CountryCodeProvider } from '../context/countrycode';
import { CartContext, useCartState } from '../hooks/test-cart.js';
export default function RootLayout({
children,
}: {
children: React.ReactNode
}) {
const cartState = useCartState();
cartState.restrict = false;
return (
<html lang="en">
<body>
<main>
<>
<CountryCodeProvider>
<CartContext.Provider value={cartState}>
{children}
</CartContext.Provider>
</CountryCodeProvider>
</>
</main>
</body>
</html>
)
}
and for test-cart.js i have the following code:
"use client"
import { useState, createContext, useContext } from 'react';
export const CartContext = createContext();
export function useCartState() {
const [cart, updateCart] = useState(defaultCart);
function addToCart({ id, item_title, item_price, restrict: boolean }) {
console.log("addToCart funtion hit")
updateCart((prev) => {
console.log("updateCart funtion hit")
})
}
return {
addToCart,
restrict: false,
}
}
export function useCart() {
const cart = useContext(CartContext);
return cart;
}
So i’ve attempted to implement cartState.restrict = false;
but unfortunately it doesn’t work.
Keep in mind that i’ve stripped out most of the code to keep this example as small as possible.
I faced same issue before. only i do thing is add use effect.
try this…
insted of
updateCart((prev) => {
console.log("updateCart funtion hit")
})
}
add useEffect()
useEffect(() => {
console.log("updateCart function hit");
updateCart((prev) => {
// your update logic here
return prev;
});
}, []);
im not sure about this.but maybe this will help