1
0
mirror of https://github.com/Unleash/unleash.git synced 2024-10-18 20:09:08 +02:00
unleash.unleash/frontend/src/utils/createLocalStorage.ts
Tymoteusz Czech 608171ce93 Improve table performance (#1061)
* improve table performance

* revert to react-router navigation
2022-06-09 11:34:55 +02:00

31 lines
936 B
TypeScript

import { basePath } from './formatPath';
import { getLocalStorageItem, setLocalStorageItem } from './storage';
export const createLocalStorage = <T extends object>(
key: string,
initialValue: T
) => {
const internalKey = `${basePath}:${key}:localStorage:v2`;
const value = (() => {
const state = getLocalStorageItem<T>(internalKey);
if (state === undefined) {
return initialValue;
}
return state;
})();
const onUpdate = (newValue: T | ((prev: T) => T)): T => {
if (newValue instanceof Function) {
const previousValue = getLocalStorageItem<T>(internalKey);
const output = newValue(previousValue ?? initialValue);
setLocalStorageItem(internalKey, output);
return output;
}
setLocalStorageItem(internalKey, newValue);
return newValue;
};
return { value, setValue: onUpdate };
};