Home > database >  How to set state to LocalStorage in React
How to set state to LocalStorage in React

Time:07-12

I'm trying to save to localstorage this cart value

const addToCart = (payload) => {
    setState({
      ...state,
      cart: [...state.cart, payload ]
    })
  }

Using this code as initialState

import { useState } from "react"
import { useLocalStorage } from "./useLocalStorage"

const useInitialState = () => {
  const [inc, setInc] = useLocalStorage("favCounter", false)

  const initialState = {
    favCounter: inc,
    cart: []
  }
  
  const [state, setState] = useState(initialState)
  
  
  const incrementFav = () => {
    setState({
      ...state,
      favCounter: state.favCounter   1
    })
    setInc(state.favCounter   1)
  }

  const decrementFav = () => {
    setState({
      ...state,
      favCounter: state.favCounter - 1
    })
    setInc(state.favCounter - 1)
  }

  const addToCart = (payload) => {
    setState({
      ...state,
      cart: [...state.cart, payload ]
    })
  }
  

  return {
    state,
    incrementFav,
    decrementFav,
    addToCart
  }
}

export default useInitialState

And this code as custom hook "useLocalStorage"

import { useState } from 'react'


export function useLocalStorage (key, initialValue) {
  const [storedValue, setValue] = useState(() => {
    try {
      const item = window.localStorage.getItem(key)
      return item !== null ? JSON.parse(item) : initialValue
    } catch (e) {
      return initialValue
    }
  })


  const setLocalStorage = value => {
    try {
      window.localStorage.setItem(key, JSON.stringify(value))
      setValue(value)
    } catch (e) {
      console.log(e)
    }
  }

  return [storedValue, setLocalStorage]
}

And I don´t know how to store the cart (array) value to localstorage as I did it with "favcounter" stored value.

CodePudding user response:

const [localCart, setLocalCart] = useLocalStorage("cartState", [])
const addToCart = (payload) => {
    setState((prevState) => {
       const newState = { ...prevState, cart: [...prevState.cart, payload ]}
       setLocalCart(newState.cart)
       return newState
    })
 }
  • Related