@alexmarqs/react-use-local-storage
Version:
React hook to persist and sync state with localStorage
109 lines (91 loc) • 3 kB
JavaScript
;
Object.defineProperty(exports, '__esModule', { value: true });
var react = require('react');
/**
* Check if we are in client/browser side.
*/
var isClient = typeof window !== 'undefined';
/**
* Initialized storage keys.
*/
var initializedStorageKeys = /*#__PURE__*/new Set();
/**
* useLocalStorage hook.
* @param key - local storage key
* @param initialValue - initial value
* @param options - hook options
* @returns a stateful value and a function to update it
*/
var useLocalStorage = function useLocalStorage(key, initialValue, options) {
if (options === void 0) {
options = {
sync: false
};
}
/**
* State to store persisted value.
*/
var _useState = react.useState(function () {
if (!isClient) {
return initialValue;
}
try {
var item = window.localStorage.getItem(key);
return item ? JSON.parse(item) : initialValue;
} catch (error) {
console.warn("An error occured when trying to READ from local storage key: " + key + ". Returning initial value.", error);
return initialValue;
}
}),
storedValue = _useState[0],
setStoredValue = _useState[1];
/**
* Detect multiple hook instances for the same key.
*/
react.useEffect(function () {
if (initializedStorageKeys.has(key)) {
throw new Error("Detected multiple instances of useLocalStorage for the same key " + key + ". Please consider using global state.");
} else {
initializedStorageKeys.add(key);
}
return function () {
initializedStorageKeys["delete"](key);
};
}, [key]);
/**
* Set new value. Functional updates supported.
*/
var setNewValue = react.useCallback(function (value) {
if (!isClient) {
console.warn('Trying to set a value inside SSR app - not supported.');
return;
}
try {
var valueToStore = value instanceof Function ? value(storedValue) : value;
setStoredValue(valueToStore);
window.localStorage.setItem(key, JSON.stringify(valueToStore));
} catch (error) {
console.warn("An error occured when trying to WRITE to local storage key: " + key + ")", error);
}
}, [key, storedValue]);
/**
* Sync changes across browser tabs/windows.
*/
react.useEffect(function () {
if (!options.sync) return;
var handleStorageUpdate = function handleStorageUpdate(event) {
if (event.key === key && event.storageArea === window.localStorage) {
var newValue = event.newValue ? JSON.parse(event.newValue) : initialValue;
setStoredValue(newValue);
}
};
window.addEventListener('storage', handleStorageUpdate);
return function () {
window.removeEventListener('storage', handleStorageUpdate);
};
}, [initialValue, key, options.sync]);
return [storedValue, setNewValue];
};
exports.default = useLocalStorage;
exports.useLocalStorage = useLocalStorage;
//# sourceMappingURL=react-use-local-storage.cjs.development.js.map