@actinc/dls
Version:
Design Language System (DLS) for ACT & Encoura front-end projects.
55 lines • 1.72 kB
JavaScript
/**
* Copyright (c) ACT, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import isFunction from 'lodash/isFunction';
import { useEffect, useState } from 'react';
export var useLocalStorage = function (key, initValue) {
if (initValue === void 0) { initValue = ''; }
var _a = useState(function () {
try {
var item = window.localStorage.getItem(key);
return item || initValue;
}
catch (err) {
console.error(err);
return initValue;
}
}), storedValue = _a[0], setStoredValue = _a[1];
var handleStorage = function (e) {
if (e.key === key && e.newValue !== storedValue) {
setStoredValue(e.newValue || initValue);
}
};
useEffect(function () {
try {
window.addEventListener('storage', handleStorage);
}
catch (err) {
console.error(err);
}
return function () {
try {
window.removeEventListener('storage', handleStorage);
}
catch (err) {
console.error(err);
}
};
}, []);
var updateStoredValue = function (value) {
try {
var valueToStore = isFunction(value) ? value(storedValue) : value;
setStoredValue(valueToStore);
window.localStorage.setItem(key, JSON.stringify(valueToStore));
}
catch (err) {
console.error(err);
}
};
return [storedValue, updateStoredValue];
};
export default useLocalStorage;
//# sourceMappingURL=useLocalStorage.js.map