Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

useLocalStorage not working with updater function #2512

Open
acontreras89 opened this issue Aug 2, 2023 · 1 comment
Open

useLocalStorage not working with updater function #2512

acontreras89 opened this issue Aug 2, 2023 · 1 comment

Comments

@acontreras89
Copy link

acontreras89 commented Aug 2, 2023

useLocalStorage is not updating the value properly when passing an updater function. This is due to state not being included in the useCallback deps for the setter function (line 82 below).

const set: Dispatch<SetStateAction<T | undefined>> = useCallback(
(valOrFunc) => {
try {
const newState =
typeof valOrFunc === 'function' ? (valOrFunc as Function)(state) : valOrFunc;
if (typeof newState === 'undefined') return;
let value: string;
if (options)
if (options.raw)
if (typeof newState === 'string') value = newState;
else value = JSON.stringify(newState);
else if (options.serializer) value = options.serializer(newState);
else value = JSON.stringify(newState);
else value = JSON.stringify(newState);
localStorage.setItem(key, value);
setState(deserializer(value));
} catch {
// If user is in private mode or has storage restriction
// localStorage can throw. Also JSON.stringify can throw.
}
},
[key, setState]
);

(I may be able to open a PR for this if I find some time to spare this or next week.)

@acontreras89 acontreras89 changed the title useLocalStorage not working with updater function useLocalStorage not working with updater function Aug 2, 2023
@acontreras89
Copy link
Author

This seems to be the same problem reported in #2273, although using pretty vague title and description. Also, PR #2277 aims at solving this, although it might need some extra work (and tests).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant