React: Setting state to local storage

Solution 1:

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',[]);

Solution 2:

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>
                      );
                    }