setValue function in useLocalStorage hook doesn't return the correct previous value
import { useLocalStorage } from 'react-use';
const Demo = () => {
const [value, setValue] = useLocalStorage('my-key', 'foo');
return (
<div>
<div>Value: {value}</div>
<button onClick={() => setValue(prev => {
// prev value is always the same
return 'bar'
)}>bar</button>
</div>
);
};
What is the expected behavior? the same behavior as in useState React hook
A little about versions:
- React: 18.2.0
react-use: 17.5.0
Same issue here.
setStoredSelectionValue((prevValue) => ({
...prevValue,
expirationDate: (new Date().getTime() + HOUR_TO_MILLISECONDS).toString(),
}));
It returns:
{
"expirationDate": "1728384977438",
}
Even if I had set other properties.
import { useLocalStorage } from 'react-use'; const Demo = () => { const [value, setValue] = useLocalStorage('my-key', 'foo'); return ( <div> <div>Value: {value}</div> <button onClick={() => setValue(prev => { // prev value is always the same return 'bar' )}>bar</button> </div> ); };What is the expected behavior? the same behavior as in useState React hook
A little about versions:
- React: 18.2.0
react-use: 17.5.0
I don't understand what's wrong, once the localstorage exists, it will not be initialized as 'foo', it will always be 'bar' at your code
use custom wrapper for useSafeLocalStorage
const useSafeLocalStorage = (key, initialValue) => { const [value, setValueRaw] = useLocalStorage(key, initialValue);
const setValue = (updater) => { if (typeof updater === 'function') { setValueRaw(updater(value)); } else { setValueRaw(updater); } };
return [value, setValue]; };
I am having the same problem! I am using version 17.6.0. The prevValue is not updated when the function executes, so it keeps saving the wrong value.
I did not expect a simple bug like this could come from a 43k+ stars repo. I was criticizing my react skills until I console.logged the prevState value. And its a wonder that this issue hasn't resolved even after a year later.