skip to Main Content

I want to pass an object array to LocalStorage. But after the first record is added, an empty array is passed, and only after the second record is added, 1 record is passed, after the third record is added, the array already has 2 records.

<button onClick={() => {
    setCustomArr([...CustomArr, { item1: null, item2: null, item3: null }])
    localStorage.setItem("localStIt", JSON.stringify(CustomArr))
  }}
>Add item</button>

This is what the code for the button looks like, when clicked I add a new entry to the array, and populate the current array into LocalStorage. And I get an array with one record only after the second click, but after the first click the array is empty.

Could you please tell me why this happens? And how to fix it?

I’m more than happy to share the code more if you need it.

Thanks!

EDIT

const [NewCustomArr, setNewCustomArr] = useState()

<button onClick={() => {
        setCustomArr([...CustomArr, { item1: null, item2: null, item3: null }])
        setNewCustomArr(CustomArr)
        localStorage.setItem("localStIt", JSON.stringify(NewCustomArr))
      }}
>Add item</button>

2

Answers


  1. Since setting state is asynchronous action, you should use setState callback pattern to get current state and set updated state properly. Here is an example:

    <button 
        onClick={() => {
            const newItem = { item1: null, item2: null, item3: null }
            setCustomArr(prevState => {
               localStorage.setItem(
                   "localStIt", 
                   JSON.stringify([...prevState, newItem])
               )
               return [...prevState, newItem]
            })
        }}
    >
        Add item
    </button>
    

    Or you can assign the updated value to a variable and use that for both operation.

    <button 
        onClick={() => {
            const newItem = { item1: null, item2: null, item3: null }
            const updated = [...customArr, newItem]
    
            setCustomArr(updated)
            localStorage.setItem(
                "localStIt", 
                JSON.stringify(updated)
            )
        }}
    >
        Add item
    </button>
    
    Login or Signup to reply.
  2. setCustomArr with useState is async operation, so you need to assign a variable for the value update and use it for both operations (local storage and state updates)

    const [NewCustomArr, setNewCustomArr] = useState()
    
    <button onClick={() => {
            //this variable is to store the updated value of the state
            const updatedArray = [...CustomArr, { item1: null, item2: null, item3: null }]
            setCustomArr(updatedArray)
            setNewCustomArr(updatedArray)
            localStorage.setItem("localStIt", JSON.stringify(updatedArray))
          }}
    >Add item</button>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search