mirror of
https://github.com/Unleash/unleash.git
synced 2024-12-28 00:06:53 +01:00
31 lines
946 B
TypeScript
31 lines
946 B
TypeScript
import { basePath } from './formatPath';
|
|
import { getLocalStorageItem, setLocalStorageItem } from './storage';
|
|
|
|
export const createLocalStorage = <T extends object | string>(
|
|
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 };
|
|
};
|