diff --git a/lib/r18gs/src/index.ts b/lib/r18gs/src/index.ts index 4fde6077..17e6947e 100644 --- a/lib/r18gs/src/index.ts +++ b/lib/r18gs/src/index.ts @@ -1,7 +1,7 @@ /* eslint-disable @typescript-eslint/non-nullable-type-assertion-style -- as ! operator is forbidden by eslint*/ import { createHook, createSetter, createSubcriber, globalRGS } from "./utils"; -import type { SetStateAction } from "./utils"; +import type { SetStateAction, ValueType } from "./utils"; export type { SetterArgType, SetStateAction, Plugin } from "./utils"; @@ -20,9 +20,15 @@ export type { SetterArgType, SetStateAction, Plugin } from "./utils"; * @param value - Initial value of the store. * @returns - A tuple (Ordered sequance of values) containing the state and a function to set the state. */ -const useRGS = (key: string, value?: T): [T, SetStateAction] => { +const useRGS = (key: string, value?: ValueType): [T, SetStateAction] => { /** Initialize the named store when invoked for the first time. */ - if (!globalRGS[key]) globalRGS[key] = [value, [], createSetter(key), createSubcriber(key)]; + if (!globalRGS[key]) + globalRGS[key] = [ + value instanceof Function ? value() : value, + [], + createSetter(key), + createSubcriber(key), + ]; return createHook(key); }; diff --git a/lib/r18gs/src/utils.ts b/lib/r18gs/src/utils.ts index 68003da7..421ec4ab 100644 --- a/lib/r18gs/src/utils.ts +++ b/lib/r18gs/src/utils.ts @@ -5,6 +5,7 @@ type Subscriber = (l: Listener) => () => void; export type SetterArgType = T | ((prevState: T) => T); export type SetStateAction = (value: SetterArgType) => void; +export type ValueType = T | (() => T); /** * This is a hack to reduce lib size + readability + not encouraging direct access to globalThis @@ -80,10 +81,11 @@ const initPlugins = async (key: string, plugins: Plugin[]) => { /** Initialize the named store when invoked for the first time. */ export const initWithPlugins = ( key: string, - value?: T, + value?: ValueType, plugins: Plugin[] = [], doNotInit = false, ) => { + value = value instanceof Function ? value() : value; if (doNotInit) { /** You will not have access to the setter until initialized */ globalRGS[key] = [value, [], null, createSubcriber(key)]; @@ -126,7 +128,7 @@ export const initWithPlugins = ( */ export const useRGSWithPlugins = ( key: string, - value?: T, + value?: ValueType, plugins?: Plugin[], doNotInit = false, ): [T, SetStateAction] => {