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
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:
Or you can assign the updated value to a variable and use that for both operation.
setCustomArr
withuseState
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)