This commit is contained in:
Malai Raja
2023-11-27 17:09:27 +05:30
commit 7113ac0681
223 changed files with 56261 additions and 0 deletions

View File

@@ -0,0 +1,33 @@
import { useState, useEffect } from 'react';
// ----------------------------------------------------------------------
export default function useLocalStorage(key, defaultValue) {
const [value, setValue] = useState(() => {
const storedValue = typeof window !== 'undefined' ? localStorage.getItem(key) : null;
return storedValue === null ? defaultValue : JSON.parse(storedValue);
});
useEffect(() => {
const listener = (e) => {
if (typeof window !== 'undefined' && e.storageArea === localStorage && e.key === key) {
setValue(e.newValue ? JSON.parse(e.newValue) : e.newValue);
}
};
window.addEventListener('storage', listener);
return () => {
window.removeEventListener('storage', listener);
};
}, [key, defaultValue]);
const setValueInLocalStorage = (newValue) => {
setValue((currentValue) => {
const result = typeof newValue === 'function' ? newValue(currentValue) : newValue;
if (typeof window !== 'undefined') localStorage.setItem(key, JSON.stringify(result));
return result;
});
};
return [value, setValueInLocalStorage];
}