Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

329
Views
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 answers
Answer question

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 Report

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!