felipemotarocha / fullstackweek-store

https://fullstackweek-store.vercel.app
240 stars 80 forks source link

LocalStorage #5

Closed gersonlamela closed 10 months ago

gersonlamela commented 11 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

felipemotarocha commented 10 months ago

Isso já foi corrigido no PR https://github.com/felipemotarocha/fullstackweek-store/pull/4.