Skip to content

Commit

Permalink
♻️ rename and refactor out comments
Browse files Browse the repository at this point in the history
  • Loading branch information
timbryandev committed Sep 29, 2023
1 parent 1c6beb3 commit 4847843
Showing 1 changed file with 6 additions and 8 deletions.
14 changes: 6 additions & 8 deletions lib/hooks/useLocalStorage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,17 +3,15 @@ import { useState } from "react";
export const useLocalStorage = (key: string, defaultValue: unknown) => {
const [localStorageValue, setLocalStorageValue] = useState(() => {
try {
// Try and retrieve any previously recorded values
const value = localStorage.getItem(key);
if (value) {
return JSON.parse(value);
const previousValue = localStorage.getItem(key);

if (previousValue === null) {
localStorage.setItem(key, JSON.stringify(defaultValue));
return defaultValue;
}

// Else, record the defaultValue and return it instead
localStorage.setItem(key, JSON.stringify(defaultValue));
return defaultValue;
return JSON.parse(previousValue);
} catch (error) {
// Fallback to the defaultValue if we can't retrieve a previous value
localStorage.setItem(key, JSON.stringify(defaultValue));
return defaultValue;
}
Expand Down

0 comments on commit 4847843

Please sign in to comment.