Initial commit
This commit is contained in:
49
hooks/useLocalStorage.ts
Normal file
49
hooks/useLocalStorage.ts
Normal file
@@ -0,0 +1,49 @@
|
||||
|
||||
import { useState, useEffect } from 'react';
|
||||
|
||||
type SetValue<T> = (value: T | ((val: T) => T)) => void;
|
||||
|
||||
export const useLocalStorage = <T,>(key: string, initialValue: T): [T, SetValue<T>] => {
|
||||
const [storedValue, setStoredValue] = useState<T>(() => {
|
||||
if (typeof window === 'undefined') {
|
||||
return initialValue;
|
||||
}
|
||||
try {
|
||||
const item = window.localStorage.getItem(key);
|
||||
return item ? JSON.parse(item) : initialValue;
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
return initialValue;
|
||||
}
|
||||
});
|
||||
|
||||
const setValue: SetValue<T> = (value) => {
|
||||
try {
|
||||
const valueToStore = value instanceof Function ? value(storedValue) : value;
|
||||
setStoredValue(valueToStore);
|
||||
if (typeof window !== 'undefined') {
|
||||
window.localStorage.setItem(key, JSON.stringify(valueToStore));
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
const handleStorageChange = (e: StorageEvent) => {
|
||||
if (e.key === key) {
|
||||
try {
|
||||
setStoredValue(e.newValue ? JSON.parse(e.newValue) : initialValue);
|
||||
} catch (error) {
|
||||
console.error(error)
|
||||
}
|
||||
}
|
||||
};
|
||||
window.addEventListener('storage', handleStorageChange);
|
||||
return () => {
|
||||
window.removeEventListener('storage', handleStorageChange);
|
||||
};
|
||||
}, [initialValue, key]);
|
||||
|
||||
return [storedValue, setValue];
|
||||
};
|
||||
Reference in New Issue
Block a user