Skip to content

Commit

Permalink
Use initializer function for useState hook in useStorage
Browse files Browse the repository at this point in the history
  • Loading branch information
emlun committed Sep 22, 2023
1 parent f7aa8d7 commit d716d2d
Showing 1 changed file with 13 additions and 10 deletions.
23 changes: 13 additions & 10 deletions src/components/useStorage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,17 +46,20 @@ function makeUseStorage<T>(
}

return (name: string, initialValue: T) => {
const storedValueStr = storage.getItem(name);
let storedValue = initialValue;
try {
if (storedValueStr !== null) {
storedValue = jsonParseTaggedBinary(storedValueStr);
const [currentValue, setValue] = useState(
() => {
const storedValueStr = storage.getItem(name);
try {
if (storedValueStr !== null) {
return jsonParseTaggedBinary(storedValueStr);
}
} catch (e) {
// Fall back to initialValue
storage.removeItem(name);
}
return initialValue;
}
} catch (e) {
// Fall back to initialValue
storage.removeItem(name);
}
const [currentValue, setValue] = useState(storedValue);
);

// Browser storage is global state, so update all useState hooks with the
// same name whenever one of them changes. The storage event is not fired
Expand Down

0 comments on commit d716d2d

Please sign in to comment.