summaryrefslogblamecommitdiff
path: root/node_modules/@phntms/use-local-state/lib/index.js
blob: 12a0de2f9e0278d5e8716183906a0e97c8a7497a (plain) (tree)













































                                                                               
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var react_1 = require("react");
var utils_1 = require("./utils");
var useLocalState = function (key, defaultValue) {
    var _a = (0, react_1.useState)(function () {
        var isCallable = function (value) {
            return typeof value === "function";
        };
        var toStore = isCallable(defaultValue) ? defaultValue() : defaultValue;
        if (!utils_1.SUPPORTED)
            return toStore;
        var item = window.localStorage.getItem(key);
        try {
            return item ? JSON.parse(item) : toStore;
        }
        catch (error) {
            return toStore;
        }
    }), value = _a[0], setValue = _a[1];
    var lastValue = (0, react_1.useRef)(value);
    lastValue.current = value;
    var setLocalStateValue = (0, react_1.useCallback)(function (newValue) {
        var isCallable = function (value) {
            return typeof value === "function";
        };
        var toStore = isCallable(newValue)
            ? newValue(lastValue.current)
            : newValue;
        if (utils_1.SUPPORTED)
            window.localStorage.setItem(key, JSON.stringify(toStore));
        setValue(toStore);
    }, [key]);
    var reset = (0, react_1.useCallback)(function () {
        var isCallable = function (value) {
            return typeof value === "function";
        };
        var toStore = isCallable(defaultValue) ? defaultValue() : defaultValue;
        setValue(toStore);
        if (utils_1.SUPPORTED)
            window.localStorage.removeItem(key);
    }, [defaultValue, key]);
    return [value, setLocalStateValue, reset];
};
exports.default = useLocalState;
//# sourceMappingURL=index.js.map