UNPKG

@actinc/dls

Version:

Design Language System (DLS) for ACT & Encoura front-end projects.

51 lines 2.53 kB
/** * Copyright (c) ACT, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import JSONParseSafe from 'json-parse-safe'; import get from 'lodash/get'; import { useEffect } from 'react'; import useLocalStorage from "../../hooks/useLocalStorage"; export var SessionStorageKeySharer = function (_a) { var keyName = _a.keyName, onSetKeyValue = _a.onSetKeyValue; var LOCAL_STORAGE_KEY_REQUEST = "REQUEST-".concat(keyName); var sessionStorageKeyValue = sessionStorage.getItem(keyName) || ''; var _b = useLocalStorage(keyName), localStorageKeyValue = _b[0], setLocalStorageSession = _b[1]; var _c = useLocalStorage(LOCAL_STORAGE_KEY_REQUEST), localStorageKeyRequest = _c[0], setLocalStorageKeyRequest = _c[1]; var sessionStorageKeyValueParsed = get(JSONParseSafe(sessionStorageKeyValue), 'value') || sessionStorageKeyValue; var localStorageKeyValueParsed = get(JSONParseSafe(localStorageKeyValue), 'value') || localStorageKeyValue; var localStorageKeyRequestParsed = get(JSONParseSafe(localStorageKeyRequest), 'value') || localStorageKeyRequest; // If we don't have the session key, request it from other tab(s) that // may have it in their Session Storage. useEffect(function () { if (!sessionStorageKeyValueParsed) { setLocalStorageKeyRequest('true'); } }, []); // If another tab requests the session key and we have it, provide it // to Local Storage and terminate the request. useEffect(function () { if (localStorageKeyRequestParsed && sessionStorageKeyValueParsed) { setLocalStorageSession(sessionStorageKeyValueParsed); } localStorage.removeItem(LOCAL_STORAGE_KEY_REQUEST); }, [localStorageKeyRequestParsed, sessionStorageKeyValueParsed]); // If we see the session key posted to Local Storage, let's set it in our // own Session Storage and remove it from Local Storage. useEffect(function () { if (localStorageKeyValueParsed && !sessionStorageKeyValueParsed) { sessionStorage.setItem(keyName, localStorageKeyValueParsed); if (onSetKeyValue) { onSetKeyValue(localStorageKeyValueParsed); } } localStorage.removeItem(keyName); }, [localStorageKeyValueParsed, sessionStorageKeyValueParsed]); return null; }; export default SessionStorageKeySharer; //# sourceMappingURL=index.js.map