summaryrefslogtreecommitdiff
path: root/node_modules/@phntms/use-local-state/lib/index.js
diff options
context:
space:
mode:
Diffstat (limited to 'node_modules/@phntms/use-local-state/lib/index.js')
-rw-r--r--node_modules/@phntms/use-local-state/lib/index.js46
1 files changed, 46 insertions, 0 deletions
diff --git a/node_modules/@phntms/use-local-state/lib/index.js b/node_modules/@phntms/use-local-state/lib/index.js
new file mode 100644
index 0000000..12a0de2
--- /dev/null
+++ b/node_modules/@phntms/use-local-state/lib/index.js
@@ -0,0 +1,46 @@
+"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 \ No newline at end of file