Skip to content

Commit

Permalink
feat: support initializer function
Browse files Browse the repository at this point in the history
  • Loading branch information
mayank1513 committed Jun 13, 2024
1 parent e844e80 commit cc8a11e
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 5 deletions.
12 changes: 9 additions & 3 deletions lib/r18gs/src/index.ts
Original file line number Diff line number Diff line change
@@ -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";

Expand All @@ -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 = <T>(key: string, value?: T): [T, SetStateAction<T>] => {
const useRGS = <T>(key: string, value?: ValueType<T>): [T, SetStateAction<T>] => {
/** 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<T>(key);
};
Expand Down
6 changes: 4 additions & 2 deletions lib/r18gs/src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ type Subscriber = (l: Listener) => () => void;

export type SetterArgType<T> = T | ((prevState: T) => T);
export type SetStateAction<T> = (value: SetterArgType<T>) => void;
export type ValueType<T> = T | (() => T);

/**
* This is a hack to reduce lib size + readability + not encouraging direct access to globalThis
Expand Down Expand Up @@ -80,10 +81,11 @@ const initPlugins = async <T>(key: string, plugins: Plugin<T>[]) => {
/** Initialize the named store when invoked for the first time. */
export const initWithPlugins = <T>(
key: string,
value?: T,
value?: ValueType<T>,
plugins: Plugin<T>[] = [],
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)];
Expand Down Expand Up @@ -126,7 +128,7 @@ export const initWithPlugins = <T>(
*/
export const useRGSWithPlugins = <T>(
key: string,
value?: T,
value?: ValueType<T>,
plugins?: Plugin<T>[],
doNotInit = false,
): [T, SetStateAction<T>] => {
Expand Down

0 comments on commit cc8a11e

Please sign in to comment.