Closed gersonlamela closed 10 months ago
Para que o localstorage funciona bem precisamos verificar se o window não é undifined então crie um hook useLocalStorage.ts:
import { useEffect, useState } from "react"; export function useLocalStorage<T>(key: string, initialValue: T | (() => T)) { const [value, setValue] = useState<T>(() => { // Perform localStorage action const jsonValue = typeof window !== "undefined" ? localStorage.getItem(key) : "[]"; if (jsonValue != null) return JSON.parse(jsonValue); if (typeof initialValue === "function") { return (initialValue as () => T)(); } else { return initialValue; } }); useEffect(() => { localStorage.setItem(key, JSON.stringify(value)); }, [key, value]); return [value, setValue] as [typeof value, typeof setValue]; }
depois mudifique o carrinho cart.ts:
const [products, setProducts] = useLocalStorage<CartProduct[]>( "@fsw-store/cart-products", [], );
SÓ ISSO SIMPLES
Isso já foi corrigido no PR https://github.com/felipemotarocha/fullstackweek-store/pull/4.
Para que o localstorage funciona bem precisamos verificar se o window não é undifined então crie um hook useLocalStorage.ts:
depois mudifique o carrinho cart.ts:
const [products, setProducts] = useLocalStorage<CartProduct[]>( "@fsw-store/cart-products", [], );
SÓ ISSO SIMPLES