Initial commit from ux_aura_central
This commit is contained in:
31
hooks/useLocalStorage.ts
Normal file
31
hooks/useLocalStorage.ts
Normal file
@@ -0,0 +1,31 @@
|
||||
// FIX: Import React to make the 'React' namespace available for type annotations.
|
||||
import React, { useState, useEffect } from 'react';
|
||||
|
||||
export function useLocalStorage<T,>(key: string, initialValue: T): [T, React.Dispatch<React.SetStateAction<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;
|
||||
}
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
try {
|
||||
const valueToStore =
|
||||
typeof storedValue === 'function'
|
||||
? storedValue(storedValue)
|
||||
: storedValue;
|
||||
window.localStorage.setItem(key, JSON.stringify(valueToStore));
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
}
|
||||
}, [key, storedValue]);
|
||||
|
||||
return [storedValue, setStoredValue];
|
||||
}
|
||||
Reference in New Issue
Block a user