mirror of
https://github.com/Unleash/unleash.git
synced 2025-01-01 00:08:27 +01:00
4167a60588
Follows up on https://github.com/Unleash/unleash/pull/4853 to add Biome to the frontend as well. ![image](https://github.com/Unleash/unleash/assets/14320932/1906faf1-fc29-4172-a4d4-b2716d72cd65) Added a few `biome-ignore` to speed up the process but we may want to check and fix them in the future.
34 lines
1.2 KiB
TypeScript
34 lines
1.2 KiB
TypeScript
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>>,
|
|
];
|
|
|
|
/**
|
|
* 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.
|
|
*
|
|
* @deprecated `utils/createLocalStorage` -- we don't need `react-hooks-global-state`
|
|
*/
|
|
export const createPersistentGlobalStateHook = <T extends object>(
|
|
key: string,
|
|
initialValue: T,
|
|
): UsePersistentGlobalState<T> => {
|
|
const container = createGlobalState<{ [key: string]: T }>({
|
|
[key]: getLocalStorageItem<T>(key) ?? initialValue,
|
|
});
|
|
|
|
const setGlobalState = (value: React.SetStateAction<T>) => {
|
|
const prev = container.getGlobalState(key);
|
|
const next = value instanceof Function ? value(prev) : value;
|
|
container.setGlobalState(key, next);
|
|
setLocalStorageItem(key, next);
|
|
};
|
|
|
|
return () => [container.useGlobalState(key)[0], setGlobalState];
|
|
};
|