react-use
Version:
Collection of React Hooks
40 lines (39 loc) • 1.47 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
var react_1 = require("react");
var util_1 = require("./util");
var useLocalStorage = function (key, initialValue, raw) {
if (!util_1.isClient) {
return [initialValue, function () { }];
}
var _a = react_1.useState(function () {
try {
var localStorageValue = localStorage.getItem(key);
if (typeof localStorageValue !== 'string') {
localStorage.setItem(key, raw ? String(initialValue) : JSON.stringify(initialValue));
return initialValue;
}
else {
return raw ? localStorageValue : JSON.parse(localStorageValue || 'null');
}
}
catch (_a) {
// If user is in private mode or has storage restriction
// localStorage can throw. JSON.parse and JSON.stringify
// can throw, too.
return initialValue;
}
}), state = _a[0], setState = _a[1];
react_1.useEffect(function () {
try {
var serializedState = raw ? String(state) : JSON.stringify(state);
localStorage.setItem(key, serializedState);
}
catch (_a) {
// If user is in private mode or has storage restriction
// localStorage can throw. Also JSON.stringify can throw.
}
}, [state]);
return [state, setState];
};
exports.default = useLocalStorage;