UNPKG

flipper-plugin

Version:

Flipper Desktop plugin SDK and components

52 lines 2.12 kB
"use strict"; /** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @format */ Object.defineProperty(exports, "__esModule", { value: true }); exports.useLocalStorageState = void 0; const react_1 = require("react"); const Tracked_1 = require("../ui/Tracked"); const useAssertStableRef_1 = require("./useAssertStableRef"); function useLocalStorageState(key, initialValue) { (0, useAssertStableRef_1.useAssertStableRef)(key, 'key'); const scope = (0, Tracked_1.useCurrentScopeName)(); const storageKey = `[useLocalStorage][${scope}]${key}`; // Based on https://usehooks.com/useLocalStorage/ (with minor adaptions) // State to store our value // Pass initial state function to useState so logic is only executed once const [storedValue, setStoredValue] = (0, react_1.useState)(() => { try { // Get from local storage by key const item = window.localStorage.getItem(storageKey); // Parse stored json or if none return initialValue return item ? JSON.parse(item) : typeof initialValue === 'function' ? initialValue() : initialValue; } catch (error) { // If error also return initialValue console.log(error); return initialValue; } }); // Return a wrapped version of useState's setter function that ... // ... persists the new value to localStorage. const setValue = (0, react_1.useCallback)((value) => { setStoredValue((storedValue) => { const nextValue = typeof value === 'function' ? value(storedValue) : value; // Save to local storage window.localStorage.setItem(storageKey, JSON.stringify(nextValue)); return nextValue; }); }, [storageKey]); return [storedValue, setValue]; } exports.useLocalStorageState = useLocalStorageState; //# sourceMappingURL=useLocalStorageState.js.map