@dr.pogodin/react-global-state 0.15.1 → 0.16.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,55 +1,38 @@
1
1
  /**
2
- * Loads and uses an item in an async collection.
2
+ * Loads and uses item(s) in an async collection.
3
3
  */
4
4
  import { type DataInEnvelopeAtPathT, type UseAsyncDataOptionsT, type UseAsyncDataResT } from './useAsyncData';
5
5
  import { type ForceT, type LockT, type TypeLock } from './utils';
6
- export type AsyncCollectionLoaderT<DataT> = (id: string, oldData: null | DataT) => DataT | Promise<DataT>;
6
+ export type AsyncCollectionLoaderT<DataT, IdT extends number | string = number | string> = (id: IdT, oldData: null | DataT, meta: {
7
+ isAborted: () => boolean;
8
+ oldDataTimestamp: number;
9
+ }) => DataT | Promise<DataT | null> | null;
10
+ export type AsyncCollectionReloaderT<DataT, IdT extends number | string = number | string> = (loader?: AsyncCollectionLoaderT<DataT, IdT>) => Promise<void>;
11
+ type CollectionItemT<DataT> = {
12
+ data: DataT | null;
13
+ loading: boolean;
14
+ timestamp: number;
15
+ };
16
+ export type UseAsyncCollectionResT<DataT, IdT extends number | string = number | string> = {
17
+ items: {
18
+ [id in IdT]: CollectionItemT<DataT>;
19
+ };
20
+ loading: boolean;
21
+ reload: AsyncCollectionReloaderT<DataT, IdT>;
22
+ timestamp: number;
23
+ };
7
24
  /**
8
- * Resolves and stores at the given `path` of global state elements of
9
- * an asynchronous data collection. In other words, it is an auxiliar wrapper
10
- * around {@link useAsyncData}, which uses a loader which resolves to different
11
- * data, based on ID argument passed in, and stores data fetched for different
12
- * IDs in the state.
13
- * @param id ID of the collection item to load & use.
14
- * @param path The global state path where entire collection should be
15
- * stored.
16
- * @param loader A loader function, which takes an
17
- * ID of data to load, and resolves to the corresponding data.
18
- * @param options Additional options.
19
- * @param options.deps An array of dependencies, which trigger
20
- * data reload when changed. Given dependency changes are watched shallowly
21
- * (similarly to the standard React's
22
- * [useEffect()](https://reactjs.org/docs/hooks-reference.html#useeffect)).
23
- * @param options.noSSR If `true`, this hook won't load data during
24
- * server-side rendering.
25
- * @param options.garbageCollectAge The maximum age of data
26
- * (in milliseconds), after which they are dropped from the state when the last
27
- * component referencing them via `useAsyncData()` hook unmounts. Defaults to
28
- * `maxage` option value.
29
- * @param options.maxage The maximum age of
30
- * data (in milliseconds) acceptable to the hook's caller. If loaded data are
31
- * older than this value, `null` is returned instead. Defaults to 5 minutes.
32
- * @param options.refreshAge The maximum age of data
33
- * (in milliseconds), after which their refreshment will be triggered when
34
- * any component referencing them via `useAsyncData()` hook (re-)renders.
35
- * Defaults to `maxage` value.
36
- * @return Returns an object with three fields: `data` holds the actual result of
37
- * last `loader` invokation, if any, and if satisfies `maxage` limit; `loading`
38
- * is a boolean flag, which is `true` if data are being loaded (the hook is
39
- * waiting for `loader` function resolution); `timestamp` (in milliseconds)
40
- * is Unix timestamp of related data currently loaded into the global state.
41
- *
42
- * Note that loaded data, if any, are stored at the given `path` of global state
43
- * along with related meta-information, using slightly different state segment
44
- * structure (see {@link AsyncDataEnvelope}). That segment of the global state
45
- * can be accessed, and even modified using other hooks,
46
- * _e.g._ {@link useGlobalState}, but doing so you may interfere with related
47
- * `useAsyncData()` hooks logic.
25
+ * Resolves and stores at the given `path` of the global state elements of
26
+ * an asynchronous data collection.
48
27
  */
49
- declare function useAsyncCollection<StateT, PathT extends null | string | undefined, IdT extends string, DataT extends DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`> = DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>>(id: IdT, path: PathT, loader: AsyncCollectionLoaderT<DataT>, options?: UseAsyncDataOptionsT): UseAsyncDataResT<DataT>;
50
- declare function useAsyncCollection<Forced extends ForceT | LockT = LockT, DataT = unknown>(id: string, path: null | string | undefined, loader: AsyncCollectionLoaderT<TypeLock<Forced, void, DataT>>, options?: UseAsyncDataOptionsT): UseAsyncDataResT<TypeLock<Forced, void, DataT>>;
28
+ declare function useAsyncCollection<StateT, PathT extends null | string | undefined, IdT extends number | string, DataT extends DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`> = DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>>(id: IdT, path: PathT, loader: AsyncCollectionLoaderT<DataT, IdT>, options?: UseAsyncDataOptionsT): UseAsyncDataResT<DataT>;
29
+ declare function useAsyncCollection<Forced extends ForceT | LockT = LockT, DataT = unknown, IdT extends number | string = number | string>(id: IdT, path: null | string | undefined, loader: AsyncCollectionLoaderT<TypeLock<Forced, void, DataT>, IdT>, options?: UseAsyncDataOptionsT): UseAsyncDataResT<TypeLock<Forced, void, DataT>>;
30
+ declare function useAsyncCollection<StateT, PathT extends null | string | undefined, IdT extends number | string, DataT extends DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`> = DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>>(id: IdT[], path: PathT, loader: AsyncCollectionLoaderT<DataT, IdT>, options?: UseAsyncDataOptionsT): UseAsyncCollectionResT<DataT, IdT>;
31
+ declare function useAsyncCollection<Forced extends ForceT | LockT = LockT, DataT = unknown, IdT extends number | string = number | string>(id: IdT[], path: null | string | undefined, loader: AsyncCollectionLoaderT<TypeLock<Forced, void, DataT>, IdT>, options?: UseAsyncDataOptionsT): UseAsyncCollectionResT<DataT, IdT>;
51
32
  export default useAsyncCollection;
52
33
  export interface UseAsyncCollectionI<StateT> {
53
- <PathT extends null | string | undefined, IdT extends string>(id: IdT, path: PathT, loader: AsyncCollectionLoaderT<DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>>, options?: UseAsyncDataOptionsT): UseAsyncDataResT<DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>>;
54
- <Forced extends ForceT | LockT = LockT, DataT = unknown>(id: string, path: null | string | undefined, loader: AsyncCollectionLoaderT<TypeLock<Forced, void, DataT>>, options?: UseAsyncDataOptionsT): UseAsyncDataResT<TypeLock<Forced, void, DataT>>;
34
+ <PathT extends null | string | undefined, IdT extends number | string>(id: IdT, path: PathT, loader: AsyncCollectionLoaderT<DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>, IdT>, options?: UseAsyncDataOptionsT): UseAsyncDataResT<DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>>;
35
+ <Forced extends ForceT | LockT = LockT, DataT = unknown, IdT extends number | string = number | string>(id: IdT, path: null | string | undefined, loader: AsyncCollectionLoaderT<TypeLock<Forced, void, DataT>, IdT>, options?: UseAsyncDataOptionsT): UseAsyncDataResT<TypeLock<Forced, void, DataT>>;
36
+ <PathT extends null | string | undefined, IdT extends number | string>(id: IdT[], path: PathT, loader: AsyncCollectionLoaderT<DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>, IdT>, options?: UseAsyncDataOptionsT): UseAsyncCollectionResT<DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>, IdT>;
37
+ <Forced extends ForceT | LockT = LockT, DataT = unknown, IdT extends number | string = number | string>(id: IdT[], path: null | string | undefined, loader: AsyncCollectionLoaderT<TypeLock<Forced, void, DataT>, IdT>, options?: UseAsyncDataOptionsT): UseAsyncCollectionResT<DataT, IdT>;
55
38
  }
@@ -2,7 +2,13 @@
2
2
  * Loads and uses async data into the GlobalState path.
3
3
  */
4
4
  import { type ForceT, type LockT, type TypeLock, type ValueAtPathT } from './utils';
5
- export type AsyncDataLoaderT<DataT> = (oldData: null | DataT) => DataT | Promise<DataT>;
5
+ import GlobalState from './GlobalState';
6
+ import SsrContext from './SsrContext';
7
+ export declare const DEFAULT_MAXAGE: number;
8
+ export type AsyncDataLoaderT<DataT> = (oldData: null | DataT, meta: {
9
+ isAborted: () => boolean;
10
+ oldDataTimestamp: number;
11
+ }) => DataT | Promise<DataT | null> | null;
6
12
  export type AsyncDataReloaderT<DataT> = (loader?: AsyncDataLoaderT<DataT>) => Promise<void>;
7
13
  export type AsyncDataEnvelopeT<DataT> = {
8
14
  data: null | DataT;
@@ -10,6 +16,7 @@ export type AsyncDataEnvelopeT<DataT> = {
10
16
  operationId: string;
11
17
  timestamp: number;
12
18
  };
19
+ export type OperationIdT = `${'C' | 'S'}${string}`;
13
20
  export declare function newAsyncDataEnvelope<DataT>(initialData?: DataT | null, { numRefs, timestamp }?: {
14
21
  numRefs?: number | undefined;
15
22
  timestamp?: number | undefined;
@@ -27,54 +34,29 @@ export type UseAsyncDataResT<DataT> = {
27
34
  reload: AsyncDataReloaderT<DataT>;
28
35
  timestamp: number;
29
36
  };
37
+ /**
38
+ * Executes the data loading operation.
39
+ * @param path Data segment path inside the global state.
40
+ * @param loader Data loader.
41
+ * @param globalState The global state instance.
42
+ * @param oldData Optional. Previously fetched data, currently stored in
43
+ * the state, if already fetched by the caller; otherwise, they will be fetched
44
+ * by the load() function itself.
45
+ * @param opIdPrefix operationId prefix to use, which should be
46
+ * 'C' at the client-side (default), or 'S' at the server-side (within SSR
47
+ * context).
48
+ * @return Resolves once the operation is done.
49
+ * @ignore
50
+ */
51
+ export declare function load<DataT>(path: null | string | undefined, loader: AsyncDataLoaderT<DataT>, globalState: GlobalState<unknown, SsrContext<unknown>>, old?: {
52
+ data: DataT | null;
53
+ timestamp: number;
54
+ }, operationId?: OperationIdT): Promise<void>;
30
55
  /**
31
56
  * Resolves asynchronous data, and stores them at given `path` of global
32
- * state. When multiple components rely on asynchronous data at the same `path`,
33
- * the data are resolved once, and reused until their age is within specified
34
- * bounds. Once the data are stale, the hook allows to refresh them. It also
35
- * garbage-collects stale data from the global state when the last component
36
- * relying on them is unmounted.
37
- * @param path Dot-delimitered state path, where data envelop is
38
- * stored.
39
- * @param loader Asynchronous function which resolves (loads)
40
- * data, which should be stored at the global state `path`. When multiple
41
- * components
42
- * use `useAsyncData()` hook for the same `path`, the library assumes that all
43
- * hook instances are called with the same `loader` (_i.e._ whichever of these
44
- * loaders is used to resolve async data, the result is acceptable to be reused
45
- * in all related components).
46
- * @param options Additional options.
47
- * @param options.deps An array of dependencies, which trigger
48
- * data reload when changed. Given dependency changes are watched shallowly
49
- * (similarly to the standard React's
50
- * [useEffect()](https://reactjs.org/docs/hooks-reference.html#useeffect)).
51
- * @param options.noSSR If `true`, this hook won't load data during
52
- * server-side rendering.
53
- * @param options.garbageCollectAge The maximum age of data
54
- * (in milliseconds), after which they are dropped from the state when the last
55
- * component referencing them via `useAsyncData()` hook unmounts. Defaults to
56
- * `maxage` option value.
57
- * @param options.maxage The maximum age of
58
- * data (in milliseconds) acceptable to the hook's caller. If loaded data are
59
- * older than this value, `null` is returned instead. Defaults to 5 minutes.
60
- * @param options.refreshAge The maximum age of data
61
- * (in milliseconds), after which their refreshment will be triggered when
62
- * any component referencing them via `useAsyncData()` hook (re-)renders.
63
- * Defaults to `maxage` value.
64
- * @return Returns an object with three fields: `data` holds the actual result of
65
- * last `loader` invokation, if any, and if satisfies `maxage` limit; `loading`
66
- * is a boolean flag, which is `true` if data are being loaded (the hook is
67
- * waiting for `loader` function resolution); `timestamp` (in milliseconds)
68
- * is Unix timestamp of related data currently loaded into the global state.
69
- *
70
- * Note that loaded data, if any, are stored at the given `path` of global state
71
- * along with related meta-information, using slightly different state segment
72
- * structure (see {@link AsyncDataEnvelopeT}). That segment of the global state
73
- * can be accessed, and even modified using other hooks,
74
- * _e.g._ {@link useGlobalState}, but doing so you may interfere with related
75
- * `useAsyncData()` hooks logic.
57
+ * state.
76
58
  */
77
- export type DataInEnvelopeAtPathT<StateT, PathT extends null | string | undefined> = ValueAtPathT<StateT, PathT, never> extends AsyncDataEnvelopeT<unknown> ? Exclude<ValueAtPathT<StateT, PathT, never>['data'], null> : void;
59
+ export type DataInEnvelopeAtPathT<StateT, PathT extends null | string | undefined> = Exclude<Extract<ValueAtPathT<StateT, PathT, void>, AsyncDataEnvelopeT<unknown>>['data'], null>;
78
60
  declare function useAsyncData<StateT, PathT extends null | string | undefined, DataT extends DataInEnvelopeAtPathT<StateT, PathT> = DataInEnvelopeAtPathT<StateT, PathT>>(path: PathT, loader: AsyncDataLoaderT<DataT>, options?: UseAsyncDataOptionsT): UseAsyncDataResT<DataT>;
79
61
  declare function useAsyncData<Forced extends ForceT | LockT = LockT, DataT = void>(path: null | string | undefined, loader: AsyncDataLoaderT<TypeLock<Forced, void, DataT>>, options?: UseAsyncDataOptionsT): UseAsyncDataResT<TypeLock<Forced, void, DataT>>;
80
62
  export { useAsyncData };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dr.pogodin/react-global-state",
3
- "version": "0.15.1",
3
+ "version": "0.16.1",
4
4
  "description": "Hook-based global state for React",
5
5
  "main": "./build/common/index.js",
6
6
  "react-native": "src/index.ts",
@@ -43,7 +43,7 @@
43
43
  "node": ">=18"
44
44
  },
45
45
  "dependencies": {
46
- "@babel/runtime": "^7.24.8",
46
+ "@babel/runtime": "^7.25.0",
47
47
  "@dr.pogodin/js-utils": "^0.0.12",
48
48
  "@types/lodash": "^4.17.7",
49
49
  "lodash": "^4.17.21",
@@ -51,15 +51,15 @@
51
51
  },
52
52
  "devDependencies": {
53
53
  "@babel/cli": "^7.24.8",
54
- "@babel/core": "^7.24.9",
55
- "@babel/eslint-parser": "^7.24.8",
56
- "@babel/eslint-plugin": "^7.24.7",
57
- "@babel/node": "^7.24.8",
54
+ "@babel/core": "^7.25.2",
55
+ "@babel/eslint-parser": "^7.25.1",
56
+ "@babel/eslint-plugin": "^7.25.1",
57
+ "@babel/node": "^7.25.0",
58
58
  "@babel/plugin-transform-runtime": "^7.24.7",
59
- "@babel/preset-env": "^7.24.8",
59
+ "@babel/preset-env": "^7.25.3",
60
60
  "@babel/preset-react": "^7.24.7",
61
61
  "@babel/preset-typescript": "^7.24.7",
62
- "@testing-library/dom": "^10.3.2",
62
+ "@testing-library/dom": "^10.4.0",
63
63
  "@testing-library/react": "^16.0.0",
64
64
  "@tsconfig/recommended": "^1.0.7",
65
65
  "@types/jest": "^29.5.12",
@@ -82,9 +82,9 @@
82
82
  "jest-environment-jsdom": "^29.7.0",
83
83
  "mockdate": "^3.0.5",
84
84
  "rimraf": "^6.0.1",
85
- "tstyche": "^2.1.0",
86
- "typescript": "^5.5.3",
87
- "typescript-eslint": "^7.16.1"
85
+ "tstyche": "^2.1.1",
86
+ "typescript": "^5.5.4",
87
+ "typescript-eslint": "^8.0.0"
88
88
  },
89
89
  "peerDependencies": {
90
90
  "react": "^18.3.1",
@@ -97,7 +97,7 @@ export default class GlobalState<
97
97
  const prevDeps = this.#dependencies[path];
98
98
  let changed = !prevDeps || prevDeps.length !== deps.length;
99
99
  for (let i = 0; !changed && i < deps.length; ++i) {
100
- changed = prevDeps[i] !== deps[i];
100
+ changed = prevDeps![i] !== deps[i];
101
101
  }
102
102
  this.#dependencies[path] = Object.freeze(deps);
103
103
  return changed;
@@ -141,7 +141,7 @@ export default class GlobalState<
141
141
  this.#nextNotifierId = undefined;
142
142
  const watchers = [...this.#watchers];
143
143
  for (let i = 0; i < watchers.length; ++i) {
144
- watchers[i]();
144
+ watchers[i]!();
145
145
  }
146
146
  });
147
147
  }
@@ -245,7 +245,7 @@ export default class GlobalState<
245
245
  let pos: any = root;
246
246
  const pathSegments = toPath(`state.${path}`);
247
247
  for (; segIdx < pathSegments.length - 1; segIdx += 1) {
248
- const seg = pathSegments[segIdx];
248
+ const seg = pathSegments[segIdx]!;
249
249
  const next = pos[seg];
250
250
  if (Array.isArray(next)) pos[seg] = [...next];
251
251
  else if (isObject(next)) pos[seg] = { ...next };
@@ -260,7 +260,7 @@ export default class GlobalState<
260
260
  }
261
261
 
262
262
  if (segIdx === pathSegments.length - 1) {
263
- pos[pathSegments[segIdx]] = value;
263
+ pos[pathSegments[segIdx]!] = value;
264
264
  }
265
265
 
266
266
  this.#currentState = root.state;
@@ -283,7 +283,7 @@ export default class GlobalState<
283
283
  const watchers = this.#watchers;
284
284
  const pos = watchers.indexOf(callback);
285
285
  if (pos >= 0) {
286
- watchers[pos] = watchers[watchers.length - 1];
286
+ watchers[pos] = watchers[watchers.length - 1]!;
287
287
  watchers.pop();
288
288
  }
289
289
  }
package/src/index.ts CHANGED
@@ -9,10 +9,16 @@ import SsrContext from './SsrContext';
9
9
 
10
10
  import useAsyncCollection, {
11
11
  type UseAsyncCollectionI,
12
+ type UseAsyncCollectionResT,
12
13
  } from './useAsyncCollection';
13
14
 
14
15
  import {
16
+ type AsyncDataEnvelopeT,
17
+ type AsyncDataLoaderT,
18
+ type AsyncDataReloaderT,
15
19
  type UseAsyncDataI,
20
+ type UseAsyncDataOptionsT,
21
+ type UseAsyncDataResT,
16
22
  newAsyncDataEnvelope,
17
23
  useAsyncData,
18
24
  } from './useAsyncData';
@@ -21,19 +27,25 @@ import useGlobalState, { type UseGlobalStateI } from './useGlobalState';
21
27
 
22
28
  export type { AsyncCollectionLoaderT } from './useAsyncCollection';
23
29
 
24
- export * from './useAsyncData';
25
-
26
30
  export type { SetterT, UseGlobalStateResT } from './useGlobalState';
27
31
 
28
32
  export type { ForceT, ValueOrInitializerT } from './utils';
29
33
 
30
34
  export {
35
+ type AsyncDataEnvelopeT,
36
+ type AsyncDataLoaderT,
37
+ type AsyncDataReloaderT,
38
+ type UseAsyncCollectionResT,
39
+ type UseAsyncDataOptionsT,
40
+ type UseAsyncDataResT,
31
41
  getGlobalState,
32
42
  getSsrContext,
33
43
  GlobalState,
34
44
  GlobalStateProvider,
45
+ newAsyncDataEnvelope,
35
46
  SsrContext,
36
47
  useAsyncCollection,
48
+ useAsyncData,
37
49
  useGlobalState,
38
50
  };
39
51