React on first click State not updated and delayed for localStorage

Viewed 10
      const [storageValue, setStorageValue] = useState(() => JSON.parse(localStorage.getItem('productCardsId')) || []);

  const localStoreHandler = productId => {
    setStorageValue(prevValue => [productId, prevValue?.[0]]);
    localStorage.setItem('productCardsId', JSON.stringify(storageValue));
  };

When I set setStorageValue with a first value I only get an empty array. After the second click, I get the value but delayed. How I can update the state on the first click? Thank you.

1 Answers

setStorageValue is an async action, so localStorage.setItem('productCardsId', JSON.stringify(storageValue)); will receive the first stale value. There are two options: One is that you update localStorage inside your state update, or have a hook that detects changes in the value and updates localStorage accordingly.

Option 1

setStorageValue(prevValue => {
  const nextValue = [productId, prevValue?.[0]]
  localStorage.setItem('productCardsId', JSON.stringify(nextValue));
  return nextValue
});

Option 2

const localStoreHandler = productId => {
  setStorageValue(prevValue => [productId, prevValue?.[0]]);
};

useEffect(() => {
  localStorage.setItem('productCardsId', JSON.stringify(storageValue));
}, [storageValue])
Related