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
|
|
|
*/
|
|
|
|
|
|
2025-06-05 07:54:57 -04:00
|
|
|
import { useCallback } from "react";
|
|
|
|
|
import { TypedEventEmitter } from "matrix-js-sdk";
|
|
|
|
|
|
|
|
|
|
import { useTypedEventEmitterState } from "./useEvents";
|
2023-08-09 13:29:45 +02:00
|
|
|
|
|
|
|
|
type LocalStorageItem = ReturnType<typeof localStorage.getItem>;
|
|
|
|
|
|
|
|
|
|
// Bus to notify other useLocalStorage consumers when an item is changed
|
2025-06-05 07:54:57 -04:00
|
|
|
export const localStorageBus = new TypedEventEmitter<
|
|
|
|
|
string,
|
|
|
|
|
{ [key: string]: () => void }
|
|
|
|
|
>();
|
2023-08-09 13:29:45 +02:00
|
|
|
|
2025-06-04 22:51:13 +02:00
|
|
|
/**
|
|
|
|
|
* Like useState, but reads from and persists the value to localStorage
|
|
|
|
|
* This hook will not update when we write to localStorage.setItem(key, value) directly.
|
|
|
|
|
* For the hook to react either use the returned setter or `setLocalStorageItemReactive`.
|
|
|
|
|
*/
|
2025-06-05 07:54:57 -04:00
|
|
|
export function useLocalStorage(
|
2023-10-11 10:42:04 -04:00
|
|
|
key: string,
|
2025-06-05 07:54:57 -04:00
|
|
|
): [LocalStorageItem, (value: string) => void] {
|
|
|
|
|
const value = useTypedEventEmitterState(
|
|
|
|
|
localStorageBus,
|
|
|
|
|
key,
|
|
|
|
|
useCallback(() => localStorage.getItem(key), [key]),
|
|
|
|
|
);
|
|
|
|
|
const setValue = useCallback(
|
|
|
|
|
(newValue: string) => setLocalStorageItemReactive(key, newValue),
|
|
|
|
|
[key],
|
2023-08-09 13:29:45 +02:00
|
|
|
);
|
|
|
|
|
|
2025-06-05 07:54:57 -04:00
|
|
|
return [value, setValue];
|
|
|
|
|
}
|
2023-08-09 13:29:45 +02:00
|
|
|
|
2025-06-04 22:51:13 +02:00
|
|
|
export const setLocalStorageItemReactive = (
|
|
|
|
|
key: string,
|
|
|
|
|
value: string,
|
|
|
|
|
): void => {
|
2023-08-09 13:29:45 +02:00
|
|
|
localStorage.setItem(key, value);
|
2025-06-05 07:54:57 -04:00
|
|
|
localStorageBus.emit(key);
|
2023-08-09 13:29:45 +02:00
|
|
|
};
|