2022-04-29 11:13:45 +00:00
|
|
|
import { Dispatch, SetStateAction, useEffect, useState } from 'react';
|
2023-11-09 04:10:43 +00:00
|
|
|
import { getData, LS_KEYS, setData } from '@ente/shared/storage/localStorage';
|
2022-04-29 11:13:45 +00:00
|
|
|
|
|
|
|
export function useLocalState<T>(
|
|
|
|
key: LS_KEYS,
|
|
|
|
initialValue?: T
|
|
|
|
): [T, Dispatch<SetStateAction<T>>] {
|
2023-03-29 14:01:03 +00:00
|
|
|
const [value, setValue] = useState<T>(initialValue);
|
2022-04-29 11:13:45 +00:00
|
|
|
|
|
|
|
useEffect(() => {
|
|
|
|
const { value } = getData(key) ?? {};
|
2024-01-10 12:41:46 +00:00
|
|
|
if (typeof value !== 'undefined') {
|
2023-03-29 14:01:03 +00:00
|
|
|
setValue(value);
|
|
|
|
}
|
2022-04-29 11:13:45 +00:00
|
|
|
}, []);
|
|
|
|
|
|
|
|
useEffect(() => {
|
2022-06-27 00:48:07 +00:00
|
|
|
if (typeof value !== 'undefined') {
|
|
|
|
setData(key, { value });
|
|
|
|
}
|
2022-04-29 11:13:45 +00:00
|
|
|
}, [value]);
|
|
|
|
|
|
|
|
return [value, setValue];
|
|
|
|
}
|