"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.useLocalStorage = useLocalStorage; var _react = require("react"); /* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License * 2.0; you may not use this file except in compliance with the Elastic License * 2.0. */ function useLocalStorage(key, defaultValue) { // This is necessary to fix a race condition issue. // It guarantees that the latest value will be always returned after the value is updated const [storageUpdate, setStorageUpdate] = (0, _react.useState)(0); const item = (0, _react.useMemo)(() => { return getFromStorage(key, defaultValue); // eslint-disable-next-line react-hooks/exhaustive-deps }, [key, storageUpdate, defaultValue]); const saveToStorage = value => { if (value === undefined) { window.localStorage.removeItem(key); } else { window.localStorage.setItem(key, JSON.stringify(value)); setStorageUpdate(storageUpdate + 1); } }; (0, _react.useEffect)(() => { function onUpdate(event) { if (event.key === key) { setStorageUpdate(storageUpdate + 1); } } window.addEventListener('storage', onUpdate); return () => { window.removeEventListener('storage', onUpdate); }; }, [key, setStorageUpdate, storageUpdate]); return [item, saveToStorage]; } function getFromStorage(keyName, defaultValue) { const storedItem = window.localStorage.getItem(keyName); if (storedItem !== null) { try { return JSON.parse(storedItem); } catch (err) { window.localStorage.removeItem(keyName); // eslint-disable-next-line no-console console.log(`Unable to decode: ${keyName}`); } } return defaultValue; }