mirror of
https://github.com/Sonny93/my-links.git
synced 2025-12-09 15:05:35 +00:00
31 lines
828 B
TypeScript
31 lines
828 B
TypeScript
import { useState } from 'react';
|
|
|
|
export function useLocalStorage(key: string, initialValue: any) {
|
|
const [storedValue, setStoredValue] = useState(() => {
|
|
if (typeof window === 'undefined') {
|
|
return initialValue;
|
|
}
|
|
try {
|
|
const item = window.localStorage.getItem(key);
|
|
return item ? JSON.parse(item) : initialValue;
|
|
} catch (error) {
|
|
console.log(error);
|
|
return initialValue;
|
|
}
|
|
});
|
|
|
|
const setValue = (value: any) => {
|
|
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.log(error);
|
|
}
|
|
};
|
|
return [storedValue, setValue];
|
|
}
|