2023-08-09 13:29:45 +02:00
|
|
|
/*
|
2024-09-06 10:22:13 +02:00
|
|
|
Copyright 2023, 2024 New Vector Ltd.
|
2023-08-09 13:29:45 +02:00
|
|
|
|
2025-02-18 17:59:58 +00:00
|
|
|
SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
|
2024-09-06 10:22:13 +02:00
|
|
|
Please see LICENSE in the repository root for full details.
|
2023-08-09 13:29:45 +02:00
|
|
|
*/
|
|
|
|
|
|
|
|
|
|
import EventEmitter from "events";
|
|
|
|
|
import { useCallback, useEffect, useState } from "react";
|
|
|
|
|
|
|
|
|
|
type LocalStorageItem = ReturnType<typeof localStorage.getItem>;
|
|
|
|
|
|
|
|
|
|
// Bus to notify other useLocalStorage consumers when an item is changed
|
|
|
|
|
export const localStorageBus = new EventEmitter();
|
|
|
|
|
|
|
|
|
|
// Like useState, but reads from and persists the value to localStorage
|
|
|
|
|
export const useLocalStorage = (
|
2023-10-11 10:42:04 -04:00
|
|
|
key: string,
|
2023-08-09 13:29:45 +02:00
|
|
|
): [LocalStorageItem, (value: string) => void] => {
|
|
|
|
|
const [value, setValue] = useState<LocalStorageItem>(() =>
|
2023-10-11 10:42:04 -04:00
|
|
|
localStorage.getItem(key),
|
2023-08-09 13:29:45 +02:00
|
|
|
);
|
|
|
|
|
|
|
|
|
|
useEffect(() => {
|
|
|
|
|
localStorageBus.on(key, setValue);
|
2024-06-04 11:20:25 -04:00
|
|
|
return (): void => {
|
2023-08-09 13:29:45 +02:00
|
|
|
localStorageBus.off(key, setValue);
|
|
|
|
|
};
|
|
|
|
|
}, [key, setValue]);
|
|
|
|
|
|
|
|
|
|
return [
|
|
|
|
|
value,
|
|
|
|
|
useCallback(
|
|
|
|
|
(newValue: string) => {
|
|
|
|
|
setValue(newValue);
|
|
|
|
|
localStorage.setItem(key, newValue);
|
|
|
|
|
localStorageBus.emit(key, newValue);
|
|
|
|
|
},
|
2023-10-11 10:42:04 -04:00
|
|
|
[key, setValue],
|
2023-08-09 13:29:45 +02:00
|
|
|
),
|
|
|
|
|
];
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
export const setLocalStorageItem = (key: string, value: string): void => {
|
|
|
|
|
localStorage.setItem(key, value);
|
|
|
|
|
localStorageBus.emit(key, value);
|
|
|
|
|
};
|