Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

324
Visualizações
React: Setting state to local storage

Am requesting help setting the cartItems state to local storage so that when never I refresh, I still get the items.

import React, { createContext, useState } from 'react';

export const AppContext = createContext();

export function Context(props) {
  const [cartItems, setCartItems] = useState([]);

  const cart = (item) => {
    const exist = cartItems.find((x) => x.id === item.id);
    if (!exist) {
      setCartItems([...cartItems, { ...item }]);
    } else {
      alert('Item Already Taken');
    }
  };

  const onAdd = (items) => {
    console.log(cartItems);
    const exist = cartItems.find((x) => x.id === items.id);
    if (exist) {
      setCartItems(
        cartItems.map((x) =>
          x.id === items.id ? { ...exist, qty: exist.qty + 1 } : x,
        ),
      );
      console.log(cartItems);
    } else {
      console.log(items);
      setCartItems([...cartItems, { ...items, qty: 1 }]);
    }
  };

  const onRemove = (product) => {
    const exist = cartItems.find((x) => x.id === product.id);
    if (exist.qty === 1) return;
    setCartItems(
      cartItems.map((x) =>
        x.id === product.id ? { ...exist, qty: exist.qty - 1 } : x,
      ),
    );
  };

  const onDeleted = (product) => {
    if (window.confirm('Do you want to delete this product?')) {
      setCartItems(cartItems.filter((x) => x.id !== product.id));
    }
  };

  const itemPrice =
    cartItems && cartItems.reduce((a, c) => a + c.qty * c.price, 0);
  const delieveryPrice = '3000';
  // eslint-disable-next-line
  const totalPrice =
    parseInt(itemPrice) + (itemPrice && parseInt(delieveryPrice));

  return (
    <AppContext.Provider
      value={{
        cartItems,
        setCartItems,
        onAdd,
        onRemove,
        cart,
        onDeleted,
        itemPrice,
        totalPrice,
        delieveryPrice,
      }}
    >
      {props.children}
    </AppContext.Provider>
  );
}
about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

You can acheive your goal by creating a customHook to initialize state with value in localStorage and alos write state on the localStorage on every update, like this:

import * as React from 'react'
function useLocalStorageState(
  key,
  defaultValue = '',
  {serialize = JSON.stringify, deserialize = JSON.parse} = {},
) {
  const [state, setState] = React.useState(() => {
    const valueInLocalStorage = window.localStorage.getItem(key)
    if (valueInLocalStorage) {
      try {
        return deserialize(valueInLocalStorage)
      } catch (error) {
        window.localStorage.removeItem(key)
      }
    }
    return typeof defaultValue === 'function' ? defaultValue() : defaultValue
  })

  const prevKeyRef = React.useRef(key)

  React.useEffect(() => {
    const prevKey = prevKeyRef.current
    if (prevKey !== key) {
      window.localStorage.removeItem(prevKey)
    }
    prevKeyRef.current = key
    window.localStorage.setItem(key, serialize(state))
  }, [key, state, serialize])

  return [state, setState]
}

and use it in your component like this:

const [cartItems, setCartItems] = useLocalStorageState('cartItems',[]);
about 4 years ago · Juan Pablo Isaza Relatório

0

You use can use localStorage.setItem().but since you have a list of items, you will first stringify it while saving and parsing when you fetch it back.
                
                
    import React, { createContext, useState } from 'react';
     export const AppContext = createContext();
                  
      export function Context(props) {
             const [cartItems, setCartItems] = useState([]);
             const onAdd = (items) => {
             const tempItems = [...cartItems];
             const exist = cartItems.findIndex((x) => x.id === items.id);
             console.log(exist);
             if (exist >= 0) {
             tempItems[exist].qty = tempItems[exist].qty + 1;
                    } 
             else {
             // setCartItems([...cartItems, { ...items, qty: 1 }]);       
              tempItems.push(items)
               }
             setCartItems(tempItems)
             localStorage.setItem("cart" , JSON.stringify(tempItems))
                  };
                    
    //to fetch data
    const getCart = () => {
        const FetchedcartItems = localStorage.getItem("cart");
        if (FetchedcartItems) {
          const parsedCartItems = JSON.parse(FetchedcartItems);
          console.log(parsedCartItems);
          setCartItems(parsedCartItems);
        }
      };
    
      useEffect(() => {
        getCart();
      }, []);
        
    
                      return (
                        <AppContext.Provider
                          value={{
                            cartItems,
                            setCartItems,
                            onAdd,
                            onRemove,
                            cart,
                            onDeleted,
                            itemPrice,
                            totalPrice,
                            delieveryPrice,
                          }}
                        >
                          {props.children}
                        </AppContext.Provider>
                      );
                    }
about 4 years ago · Juan Pablo Isaza Relatório

0

What I do, usually, is to set up a file just to handle localStorage, so in your case, cart.services.js. Inside that file you can create functions that receive, save, read, modify and etc the localStorage.

Something like this:

const getCart = () => {
  return JSON.parse(localStorage.getItem("cart"));
};

const setCart = (cart) => {
  localStorage.setItem("cart", JSON.stringify(cart));
};

const removeUser = () => {
  localStorage.removeItem("cart");
};

Obviously you might need some more fancier logic to add items based on previous state, etc, but the basic logic is that and it's super straightforward.

More info: https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda