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

Allows aborting state updates by returning the old value in useLocalStorage #635

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 9 additions & 1 deletion packages/usehooks-ts/src/useLocalStorage/useLocalStorage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -128,8 +128,16 @@ export function useLocalStorage<T>(
}

try {
// Read the old value to compare with the new
const oldValue = readValue();

// Allow value to be a function so we have the same API as useState
const newValue = value instanceof Function ? value(readValue()) : value
const newValue = value instanceof Function ? value(oldValue) : value

// Check if the new value is equal to old and if so, cancel update
if (Object.is(newValue, oldValue)) {
return;
}

// Save to local storage
window.localStorage.setItem(key, serializer(newValue))
Expand Down