Files
ThreadNet-Web/src/hooks/useLocalStorageState.ts
T

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

40 lines
1.1 KiB
TypeScript
Raw Normal View History

2020-08-27 10:27:27 +01:00
/*
2024-09-09 14:57:16 +01:00
Copyright 2024 New Vector Ltd.
2020-08-27 10:56:04 +01:00
Copyright 2020 The Matrix.org Foundation C.I.C.
2020-08-27 10:27:27 +01:00
2024-09-09 14:57:16 +01:00
SPDX-License-Identifier: AGPL-3.0-only OR GPL-3.0-only
Please see LICENSE files in the repository root for full details.
2020-08-27 10:27:27 +01:00
*/
import { Dispatch, useCallback, useEffect, useState } from "react";
2020-08-27 10:27:27 +01:00
const getValue = <T>(key: string, initialValue: T): T => {
try {
const item = window.localStorage.getItem(key);
return item ? JSON.parse(item) : initialValue;
2024-10-16 16:43:07 +01:00
} catch {
2020-08-27 10:27:27 +01:00
return initialValue;
}
};
// Hook behaving like useState but persisting the value to localStorage. Returns same as useState
export const useLocalStorageState = <T>(key: string, initialValue: T): [T, Dispatch<T>] => {
2020-08-27 10:27:27 +01:00
const lsKey = "mx_" + key;
const [value, setValue] = useState<T>(getValue(lsKey, initialValue));
useEffect(() => {
setValue(getValue(lsKey, initialValue));
}, [lsKey, initialValue]);
const _setValue: Dispatch<T> = useCallback(
2020-08-27 10:27:27 +01:00
(v: T) => {
window.localStorage.setItem(lsKey, JSON.stringify(v));
setValue(v);
},
[lsKey],
);
return [value, _setValue];
};