2022-02-08 12:06:25 +01:00
|
|
|
import React from 'react';
|
|
|
|
import { createGlobalState } from 'react-hooks-global-state';
|
|
|
|
import { getLocalStorageItem, setLocalStorageItem } from '../utils/storage';
|
|
|
|
|
|
|
|
type UsePersistentGlobalState<T> = () => [
|
|
|
|
value: T,
|
|
|
|
setValue: React.Dispatch<React.SetStateAction<T>>
|
|
|
|
];
|
|
|
|
|
2022-05-18 11:56:55 +02:00
|
|
|
/**
|
|
|
|
* Create a hook that stores global state (shared across all hook instances).
|
|
|
|
* The state is also persisted to localStorage and restored on page load.
|
|
|
|
* The localStorage state is not synced between tabs.
|
|
|
|
*
|
2023-02-17 13:10:27 +01:00
|
|
|
* @deprecated `utils/createLocalStorage` -- we don't need `react-hooks-global-state`
|
2022-05-18 11:56:55 +02:00
|
|
|
*/
|
2022-02-23 15:08:44 +01:00
|
|
|
export const createPersistentGlobalStateHook = <T extends object>(
|
2022-02-08 12:06:25 +01:00
|
|
|
key: string,
|
|
|
|
initialValue: T
|
|
|
|
): UsePersistentGlobalState<T> => {
|
|
|
|
const container = createGlobalState<{ [key: string]: T }>({
|
2022-05-25 10:14:22 +02:00
|
|
|
[key]: getLocalStorageItem<T>(key) ?? initialValue,
|
2022-02-08 12:06:25 +01:00
|
|
|
});
|
|
|
|
|
|
|
|
const setGlobalState = (value: React.SetStateAction<T>) => {
|
|
|
|
const prev = container.getGlobalState(key);
|
2022-03-03 10:01:04 +01:00
|
|
|
const next = value instanceof Function ? value(prev) : value;
|
2022-02-08 12:06:25 +01:00
|
|
|
container.setGlobalState(key, next);
|
|
|
|
setLocalStorageItem(key, next);
|
|
|
|
};
|
|
|
|
|
|
|
|
return () => [container.useGlobalState(key)[0], setGlobalState];
|
|
|
|
};
|