fix(rental): no setState in effect for cart hydration
All checks were successful
CI / test (push) Successful in 2m15s
All checks were successful
CI / test (push) Successful in 2m15s
This commit is contained in:
commit
d42584cc4c
1 changed files with 8 additions and 7 deletions
|
|
@ -4,7 +4,6 @@ import {
|
|||
createContext,
|
||||
useCallback,
|
||||
useContext,
|
||||
useEffect,
|
||||
useMemo,
|
||||
useState,
|
||||
type ReactNode,
|
||||
|
|
@ -44,12 +43,14 @@ function writeCookieClient(cart: Cart): void {
|
|||
}
|
||||
|
||||
export function RentalCartProvider({ children, initial }: { children: ReactNode; initial?: Cart }) {
|
||||
const [cart, setCart] = useState<Cart>(initial ?? EMPTY_CART);
|
||||
|
||||
// Hydrate depuis cookie au mount (au cas où le panier a changé dans un autre onglet)
|
||||
useEffect(() => {
|
||||
setCart(readCookieClient());
|
||||
}, []);
|
||||
// Initial vient du serveur (cookie lu côté serveur). Sur le client on relit le
|
||||
// cookie une seule fois via lazy initializer pour rester cohérent si un autre
|
||||
// onglet a modifié le panier entre le render serveur et l'hydration.
|
||||
const [cart, setCart] = useState<Cart>(() => {
|
||||
if (typeof document === "undefined") return initial ?? EMPTY_CART;
|
||||
const fromCookie = readCookieClient();
|
||||
return fromCookie.items.length > 0 ? fromCookie : initial ?? EMPTY_CART;
|
||||
});
|
||||
|
||||
const persist = useCallback((next: Cart) => {
|
||||
setCart(next);
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue