react-redux-cache 0.1.1 → 0.2.0

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.
package/README.md CHANGED
@@ -1,3 +1,11 @@
1
+ ### Donations 🙌
2
+
3
+ **BTC:** bc1qs0sq7agz5j30qnqz9m60xj4tt8th6aazgw7kxr \
4
+ **ETH:** 0x1D834755b5e889703930AC9b784CB625B3cd833E \
5
+ **USDT(Tron):** TPrCq8LxGykQ4as3o1oB8V7x1w2YPU2o5n \
6
+ **TON:** EQAtBuFWI3H_LpHfEToil4iYemtfmyzlaJpahM3tFSoxojvV \
7
+ **DOGE:** D7GMQdKhKC9ymbT9PtcetSFTQjyPRRfkwT
8
+
1
9
  # react-redux-cache
2
10
 
3
11
  **Powerful** yet **lightweight** data fetching and caching library that supports **normalization** unlike `react-query` and `rtk-query`, while having similar but very simple interface. Built on top of `redux`, fully typed and written on Typescript. Can be considered as `ApolloClient` for protocols other than `GraphQL`.
@@ -28,21 +36,28 @@ Remains **full control** of redux state with ability to write custom selectors,
28
36
  npm add react-redux-cache react redux react-redux
29
37
  ```
30
38
  ### Initialization
31
- The only function that needs to be imported is `createCache`, which creates fully typed reducer, hooks, actions, selectors and utils to be used in the app. Only **single** cache reducer per store is supported currenlty.
39
+ The only function that needs to be imported is `createCache`, which creates fully typed reducer, hooks, actions, selectors and utils to be used in the app. You can create as many caches as needed, but keep in mind that normalization is not shared between them.
32
40
  All typenames, queries and mutations should be passed while initializing the cache for proper typing.
33
41
  #### cache.ts
34
42
  ```typescript
35
43
  export const {
44
+ cache,
36
45
  reducer,
37
46
  hooks: {useClient, useMutation, useQuery, useSelectEntityById},
38
47
  // Actions, selectors and utils may be not used at all
39
48
  selectors: {entitiesSelector, entitiesByTypenameSelector},
40
- actions: {updateQueryStateAndEntities, updateMutationStateAndEntities, mergeEntityChanges},
49
+ actions: {
50
+ updateQueryStateAndEntities,
51
+ updateMutationStateAndEntities,
52
+ mergeEntityChanges,
53
+ clearQueryState,
54
+ clearMutationState,
55
+ },
41
56
  utils: {applyEntityChanges},
42
57
  } = createCache({
43
- // This selector should return the cache state based on the path to its reducer.
44
- cacheStateSelector: (state) => state.cache,
45
- // Typenames provide a mapping of all typenames to their entity types, which is needed for normalization.
58
+ // Used as prefix for actions and in default cacheStateSelector for selecting cache state from redux state.
59
+ name: 'cache',
60
+ // Typenames provide a mapping of all typenames to their entity types, which is needed for proper typing and normalization.
46
61
  // Empty objects with type casting can be used as values.
47
62
  typenames: {
48
63
  users: {} as User, // here `users` entities will have type `User`
@@ -60,11 +75,12 @@ export const {
60
75
  ```
61
76
  #### store.ts
62
77
  ```typescript
63
- // Create store as usual, passing the new cache reducer
64
- // under the key, previously used in cacheStateSelector
78
+ // Create store as usual, passing the new cache reducer under the name of the cache.
79
+ // If some other redux structure is needed, provide custom cacheStateSelector when creating cache.
65
80
  const store = configureStore({
66
81
  reducer: {
67
- cache: reducer,
82
+ [cache.name]: reducer,
83
+ ...
68
84
  }
69
85
  })
70
86
  ```
@@ -0,0 +1,50 @@
1
+ import type { EntityChanges, Key, QueryMutationState, Typenames } from './types';
2
+ export type ActionMap<N extends string, T extends Typenames, QR, MR> = ReturnType<typeof createActions<N, T, QR, MR>>;
3
+ export declare const createActions: <N extends string, T extends Typenames, QR, MR>(name: N) => {
4
+ updateQueryStateAndEntities: {
5
+ <K extends keyof QR>(queryKey: K, queryCacheKey: Key, state?: Partial<QueryMutationState<QR[K]>> | undefined, entityChagnes?: EntityChanges<T> | undefined): {
6
+ type: `@rrc/${N}/updateQueryStateAndEntities`;
7
+ queryKey: K;
8
+ queryCacheKey: Key;
9
+ state: Partial<QueryMutationState<QR[K]>> | undefined;
10
+ entityChagnes: EntityChanges<T> | undefined;
11
+ };
12
+ type: `@rrc/${N}/updateQueryStateAndEntities`;
13
+ };
14
+ updateMutationStateAndEntities: {
15
+ <K_1 extends keyof MR>(mutationKey: K_1, state?: Partial<QueryMutationState<MR[K_1]>> | undefined, entityChagnes?: EntityChanges<T> | undefined): {
16
+ type: `@rrc/${N}/updateMutationStateAndEntities`;
17
+ mutationKey: K_1;
18
+ state: Partial<QueryMutationState<MR[K_1]>> | undefined;
19
+ entityChagnes: EntityChanges<T> | undefined;
20
+ };
21
+ type: `@rrc/${N}/updateMutationStateAndEntities`;
22
+ };
23
+ mergeEntityChanges: {
24
+ (changes: EntityChanges<T>): {
25
+ type: `@rrc/${N}/mergeEntityChanges`;
26
+ changes: EntityChanges<T>;
27
+ };
28
+ type: `@rrc/${N}/mergeEntityChanges`;
29
+ };
30
+ clearQueryState: {
31
+ <K_2 extends keyof QR>(queryKeys: {
32
+ key: K_2;
33
+ cacheKey?: Key | undefined;
34
+ }[]): {
35
+ type: `@rrc/${N}/clearQueryState`;
36
+ queryKeys: {
37
+ key: K_2;
38
+ cacheKey?: Key | undefined;
39
+ }[];
40
+ };
41
+ type: `@rrc/${N}/clearQueryState`;
42
+ };
43
+ clearMutationState: {
44
+ <K_3 extends keyof MR>(mutationKeys: K_3[]): {
45
+ type: `@rrc/${N}/clearMutationState`;
46
+ mutationKeys: K_3[];
47
+ };
48
+ type: `@rrc/${N}/clearMutationState`;
49
+ };
50
+ };
@@ -0,0 +1,56 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createActions = void 0;
4
+ const utilsAndConstants_1 = require("./utilsAndConstants");
5
+ const createActions = (name) => {
6
+ const actionPrefix = `@${utilsAndConstants_1.PACKAGE_SHORT_NAME}/${name}/`;
7
+ const updateQueryStateAndEntitiesType = `${actionPrefix}updateQueryStateAndEntities`;
8
+ /** Updates query state, and optionally merges entity changes in a single action. */
9
+ const updateQueryStateAndEntities = (queryKey, queryCacheKey, state, entityChagnes) => ({
10
+ type: updateQueryStateAndEntitiesType,
11
+ queryKey,
12
+ queryCacheKey,
13
+ state,
14
+ entityChagnes,
15
+ });
16
+ updateQueryStateAndEntities.type = updateQueryStateAndEntitiesType;
17
+ const updateMutationStateAndEntitiesType = `${actionPrefix}updateMutationStateAndEntities`;
18
+ /** Updates mutation state, and optionally merges entity changes in a single action. */
19
+ const updateMutationStateAndEntities = (mutationKey, state, entityChagnes) => ({
20
+ type: updateMutationStateAndEntitiesType,
21
+ mutationKey,
22
+ state,
23
+ entityChagnes,
24
+ });
25
+ updateMutationStateAndEntities.type = updateMutationStateAndEntitiesType;
26
+ const mergeEntityChangesType = `${actionPrefix}mergeEntityChanges`;
27
+ /** Merge EntityChanges to the state. */
28
+ const mergeEntityChanges = (changes) => ({
29
+ type: mergeEntityChangesType,
30
+ changes,
31
+ });
32
+ mergeEntityChanges.type = mergeEntityChangesType;
33
+ const clearQueryStateType = `${actionPrefix}clearQueryState`;
34
+ /** Clear states for provided query keys and cache keys.
35
+ * If cache key for query key is not provided, the whole state for query key is cleared. */
36
+ const clearQueryState = (queryKeys) => ({
37
+ type: clearQueryStateType,
38
+ queryKeys,
39
+ });
40
+ clearQueryState.type = clearQueryStateType;
41
+ const clearMutationStateType = `${actionPrefix}clearMutationState`;
42
+ /** Clear states for provided mutation keys. */
43
+ const clearMutationState = (mutationKeys) => ({
44
+ type: clearMutationStateType,
45
+ mutationKeys,
46
+ });
47
+ clearMutationState.type = clearMutationStateType;
48
+ return {
49
+ updateQueryStateAndEntities,
50
+ updateMutationStateAndEntities,
51
+ mergeEntityChanges,
52
+ clearQueryState,
53
+ clearMutationState,
54
+ };
55
+ };
56
+ exports.createActions = createActions;
@@ -1,4 +1,3 @@
1
- import { clearMutationState, clearQueryState, mergeEntityChanges, updateMutationStateAndEntities, updateQueryStateAndEntities } from './actions';
2
1
  import type { Cache, EntitiesMap, Key, MutationResult, OptionalPartial, QueryOptions, QueryResult, Typenames } from './types';
3
2
  import { useMutation } from './useMutation';
4
3
  import { useQuery } from './useQuery';
@@ -6,78 +5,87 @@ import { applyEntityChanges } from './utilsAndConstants';
6
5
  /**
7
6
  * Creates reducer, actions and hooks for managing queries and mutations through redux cache.
8
7
  */
9
- export declare const createCache: <T extends Typenames, QP, QR, MP, MR>(partialCache: OptionalPartial<Cache<T, QP, QR, MP, MR>, "queries" | "mutations" | "options">) => {
10
- cache: Cache<T, QP, QR, MP, MR>;
8
+ export declare const createCache: <N extends string, T extends Typenames, QP, QR, MP, MR>(partialCache: OptionalPartial<Cache<N, T, QP, QR, MP, MR>, "options" | "queries" | "mutations" | "cacheStateSelector">) => {
9
+ cache: Cache<N, T, QP, QR, MP, MR>;
11
10
  /** Reducer of the cache, should be added to redux store. */
12
11
  reducer: (state: {
13
12
  entities: EntitiesMap<T>;
14
13
  queries: { [QK in keyof QR]: import("./types").Dict<import("./types").QueryMutationState<QR[QK]>>; };
15
14
  mutations: { [MK in keyof MR]: import("./types").QueryMutationState<MR[MK]>; };
16
15
  } | undefined, action: {
17
- type: `${string}MERGE_ENTITY_CHANGES`;
18
- changes: import("./types").EntityChanges<T>;
19
- } | {
20
- type: `${string}UPDATE_QUERY_STATE_AND_ENTITIES`;
16
+ type: `@rrc/${N}/updateQueryStateAndEntities`;
21
17
  queryKey: keyof QR;
22
18
  queryCacheKey: Key;
23
19
  state: Partial<import("./types").QueryMutationState<QR[keyof QR]>> | undefined;
24
20
  entityChagnes: import("./types").EntityChanges<T> | undefined;
25
21
  } | {
26
- type: `${string}UPDATE_MUTATION_STATE_AND_ENTITIES`;
22
+ type: `@rrc/${N}/updateMutationStateAndEntities`;
27
23
  mutationKey: keyof MR;
28
24
  state: Partial<import("./types").QueryMutationState<MR[keyof MR]>> | undefined;
29
25
  entityChagnes: import("./types").EntityChanges<T> | undefined;
30
26
  } | {
31
- type: `${string}CLEAR_QUERY_STATE`;
27
+ type: `@rrc/${N}/mergeEntityChanges`;
28
+ changes: import("./types").EntityChanges<T>;
29
+ } | {
30
+ type: `@rrc/${N}/clearQueryState`;
32
31
  queryKeys: {
33
32
  key: keyof QR;
34
33
  cacheKey?: Key | undefined;
35
34
  }[];
36
35
  } | {
37
- type: `${string}CLEAR_MUTATION_STATE`;
38
- mutationKeys: (keyof MR)[];
36
+ type: `@rrc/${N}/clearMutationState`;
37
+ mutationKeys: (keyof MR)[]; /** Select all entities of provided typename. */
39
38
  }) => {
40
39
  entities: EntitiesMap<T>;
41
40
  queries: { [QK in keyof QR]: import("./types").Dict<import("./types").QueryMutationState<QR[QK]>>; };
42
41
  mutations: { [MK in keyof MR]: import("./types").QueryMutationState<MR[MK]>; };
43
42
  };
44
43
  actions: {
45
- /** Updates query state, and optionally merges entity changes in a single action. */
46
- updateQueryStateAndEntities: <K extends keyof QR>(queryKey: K, queryCacheKey: Key, state?: Partial<import("./types").QueryMutationState<QR[K]>> | undefined, entityChagnes?: import("./types").EntityChanges<T> | undefined) => {
47
- type: `${string}UPDATE_QUERY_STATE_AND_ENTITIES`;
48
- queryKey: K;
49
- queryCacheKey: Key;
50
- state: Partial<import("./types").QueryMutationState<QR[K]>> | undefined;
51
- entityChagnes: import("./types").EntityChanges<T> | undefined;
44
+ updateQueryStateAndEntities: {
45
+ <K extends keyof QR>(queryKey: K, queryCacheKey: Key, state?: Partial<import("./types").QueryMutationState<QR[K]>> | undefined, entityChagnes?: import("./types").EntityChanges<T> | undefined): {
46
+ type: `@rrc/${N}/updateQueryStateAndEntities`;
47
+ queryKey: K;
48
+ queryCacheKey: Key;
49
+ state: Partial<import("./types").QueryMutationState<QR[K]>> | undefined;
50
+ entityChagnes: import("./types").EntityChanges<T> | undefined;
51
+ };
52
+ type: `@rrc/${N}/updateQueryStateAndEntities`;
52
53
  };
53
- /** Updates mutation state, and optionally merges entity changes in a single action. */
54
- updateMutationStateAndEntities: <K_1 extends keyof MR>(mutationKey: K_1, state?: Partial<import("./types").QueryMutationState<MR[K_1]>> | undefined, entityChagnes?: import("./types").EntityChanges<T> | undefined) => {
55
- type: `${string}UPDATE_MUTATION_STATE_AND_ENTITIES`;
56
- mutationKey: K_1;
57
- state: Partial<import("./types").QueryMutationState<MR[K_1]>> | undefined;
58
- entityChagnes: import("./types").EntityChanges<T> | undefined;
54
+ updateMutationStateAndEntities: {
55
+ <K_1 extends keyof MR>(mutationKey: K_1, state?: Partial<import("./types").QueryMutationState<MR[K_1]>> | undefined, entityChagnes?: import("./types").EntityChanges<T> | undefined): {
56
+ type: `@rrc/${N}/updateMutationStateAndEntities`;
57
+ mutationKey: K_1;
58
+ state: Partial<import("./types").QueryMutationState<MR[K_1]>> | undefined;
59
+ entityChagnes: import("./types").EntityChanges<T> | undefined;
60
+ };
61
+ type: `@rrc/${N}/updateMutationStateAndEntities`;
59
62
  };
60
- /** Merge EntityChanges to the state. */
61
- mergeEntityChanges: (changes: import("./types").EntityChanges<T>) => {
62
- type: `${string}MERGE_ENTITY_CHANGES`;
63
- changes: import("./types").EntityChanges<T>;
63
+ mergeEntityChanges: {
64
+ (changes: import("./types").EntityChanges<T>): {
65
+ type: `@rrc/${N}/mergeEntityChanges`;
66
+ changes: import("./types").EntityChanges<T>;
67
+ };
68
+ type: `@rrc/${N}/mergeEntityChanges`;
64
69
  };
65
- /** Clear states for provided query keys and cache keys.
66
- * If cache key for query key is not provided, the whole state for query key is cleared. */
67
- clearQueryState: <K_2 extends keyof QR>(queryKeys: {
68
- key: K_2;
69
- cacheKey?: Key | undefined;
70
- }[]) => {
71
- type: `${string}CLEAR_QUERY_STATE`;
72
- queryKeys: {
70
+ clearQueryState: {
71
+ <K_2 extends keyof QR>(queryKeys: {
73
72
  key: K_2;
74
73
  cacheKey?: Key | undefined;
75
- }[];
74
+ }[]): {
75
+ type: `@rrc/${N}/clearQueryState`;
76
+ queryKeys: {
77
+ key: K_2;
78
+ cacheKey?: Key | undefined;
79
+ }[];
80
+ };
81
+ type: `@rrc/${N}/clearQueryState`;
76
82
  };
77
- /** Clear states for provided mutation keys. */
78
- clearMutationState: <K_3 extends keyof MR>(mutationKeys: K_3[]) => {
79
- type: `${string}CLEAR_MUTATION_STATE`;
80
- mutationKeys: K_3[];
83
+ clearMutationState: {
84
+ <K_3 extends keyof MR>(mutationKeys: K_3[]): {
85
+ type: `@rrc/${N}/clearMutationState`;
86
+ mutationKeys: K_3[]; /** Select all entities of provided typename. */
87
+ };
88
+ type: `@rrc/${N}/clearMutationState`;
81
89
  };
82
90
  };
83
91
  selectors: {
@@ -89,20 +97,20 @@ export declare const createCache: <T extends Typenames, QP, QR, MP, MR>(partialC
89
97
  hooks: {
90
98
  /** Returns client object with query function */
91
99
  useClient: () => {
92
- query: <QK_1 extends keyof QP | keyof QR>(options: QueryOptions<T, QP, QR, MP, MR, QK_1>) => Promise<QueryResult<QK_1 extends keyof QP & keyof QR ? QR[QK_1] : never>>;
100
+ query: <QK_1 extends keyof QR | keyof QP>(options: QueryOptions<T, QP, QR, MR, QK_1>) => Promise<QueryResult<QK_1 extends keyof QP & keyof QR ? QR[QK_1] : never>>;
93
101
  mutate: <MK_1 extends keyof MP | keyof MR>(options: {
94
102
  mutation: MK_1;
95
103
  params: MK_1 extends keyof MP & keyof MR ? MP[MK_1] : never;
96
104
  }) => Promise<MutationResult<MK_1 extends keyof MP & keyof MR ? MR[MK_1] : never>>;
97
105
  };
98
106
  /** Fetches query when params change and subscribes to query state. */
99
- useQuery: <QK_2 extends keyof QP | keyof QR>(options: import("./types").UseQueryOptions<T, QP, QR, MP, MR, QK_2>) => readonly [import("./types").QueryMutationState<QK_2 extends keyof QP & keyof QR ? QR[QK_2] : never>, () => Promise<void>];
107
+ useQuery: <QK_2 extends keyof QR | keyof QP>(options: import("./types").UseQueryOptions<T, QP, QR, MR, QK_2>) => readonly [import("./types").QueryMutationState<QK_2 extends keyof QP & keyof QR ? QR[QK_2] : never>, () => Promise<void>];
100
108
  /** Subscribes to provided mutation state and provides mutate function. */
101
109
  useMutation: <MK_2 extends keyof MP | keyof MR>(options: {
102
110
  mutation: MK_2;
103
111
  }) => readonly [(params: MK_2 extends keyof MP & keyof MR ? MP[MK_2] : never) => Promise<void>, import("./types").QueryMutationState<MK_2 extends keyof MP & keyof MR ? MP[MK_2] : never>, () => boolean];
104
112
  /** Selects entity by id and subscribes to the changes. */
105
- useSelectEntityById: <K_5 extends keyof T>(id: Key | null | undefined, typename: K_5) => T[K_5] | undefined;
113
+ useSelectEntityById: <TN_1 extends keyof T>(id: Key | null | undefined, typename: TN_1) => T[TN_1] | undefined;
106
114
  };
107
115
  utils: {
108
116
  applyEntityChanges: (entities: EntitiesMap<T>, changes: import("./types").EntityChanges<T>) => EntitiesMap<T> | undefined;
@@ -3,7 +3,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.createCache = void 0;
4
4
  const react_1 = require("react");
5
5
  const react_redux_1 = require("react-redux");
6
- const actions_1 = require("./actions");
6
+ const createActions_1 = require("./createActions");
7
7
  const mutate_1 = require("./mutate");
8
8
  const query_1 = require("./query");
9
9
  const reducer_1 = require("./reducer");
@@ -14,16 +14,18 @@ const utilsAndConstants_1 = require("./utilsAndConstants");
14
14
  * Creates reducer, actions and hooks for managing queries and mutations through redux cache.
15
15
  */
16
16
  const createCache = (partialCache) => {
17
- var _a, _b, _c, _d, _e;
18
- var _f, _g;
17
+ var _a, _b, _c, _d, _e, _f;
18
+ var _g, _h;
19
19
  const abortControllers = new WeakMap();
20
20
  // provide all optional fields
21
21
  (_a = partialCache.options) !== null && _a !== void 0 ? _a : (partialCache.options = {});
22
- (_b = (_f = partialCache.options).logsEnabled) !== null && _b !== void 0 ? _b : (_f.logsEnabled = false);
23
- (_c = (_g = partialCache.options).validateFunctionArguments) !== null && _c !== void 0 ? _c : (_g.validateFunctionArguments = utilsAndConstants_1.IS_DEV);
22
+ (_b = (_g = partialCache.options).logsEnabled) !== null && _b !== void 0 ? _b : (_g.logsEnabled = false);
23
+ (_c = (_h = partialCache.options).validateFunctionArguments) !== null && _c !== void 0 ? _c : (_h.validateFunctionArguments = utilsAndConstants_1.IS_DEV);
24
24
  (_d = partialCache.queries) !== null && _d !== void 0 ? _d : (partialCache.queries = {});
25
25
  (_e = partialCache.mutations) !== null && _e !== void 0 ? _e : (partialCache.mutations = {});
26
- // @ts-expect-error for testing
26
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
27
+ (_f = partialCache.cacheStateSelector) !== null && _f !== void 0 ? _f : (partialCache.cacheStateSelector = (state) => state[cache.name]);
28
+ // @ts-expect-error private field for testing
27
29
  partialCache.abortControllers = abortControllers;
28
30
  const cache = partialCache;
29
31
  // make selectors
@@ -34,23 +36,12 @@ const createCache = (partialCache) => {
34
36
  result[x] = (state) => cache.cacheStateSelector(state).entities[x];
35
37
  return result;
36
38
  }, {});
39
+ const actions = (0, createActions_1.createActions)(cache.name);
37
40
  return {
38
41
  cache,
39
42
  /** Reducer of the cache, should be added to redux store. */
40
- reducer: (0, reducer_1.createCacheReducer)(cache.typenames, cache.queries, cache.mutations, cache.options),
41
- actions: {
42
- /** Updates query state, and optionally merges entity changes in a single action. */
43
- updateQueryStateAndEntities: actions_1.updateQueryStateAndEntities,
44
- /** Updates mutation state, and optionally merges entity changes in a single action. */
45
- updateMutationStateAndEntities: actions_1.updateMutationStateAndEntities,
46
- /** Merge EntityChanges to the state. */
47
- mergeEntityChanges: actions_1.mergeEntityChanges,
48
- /** Clear states for provided query keys and cache keys.
49
- * If cache key for query key is not provided, the whole state for query key is cleared. */
50
- clearQueryState: actions_1.clearQueryState,
51
- /** Clear states for provided mutation keys. */
52
- clearMutationState: actions_1.clearMutationState,
53
- },
43
+ reducer: (0, reducer_1.createCacheReducer)(actions, cache.typenames, Object.keys(cache.queries), cache.options),
44
+ actions,
54
45
  selectors: {
55
46
  /** Select all entities from the state. */
56
47
  entitiesSelector,
@@ -71,22 +62,24 @@ const createCache = (partialCache) => {
71
62
  const getCacheKey = (_a = cache.queries[queryKey].getCacheKey) !== null && _a !== void 0 ? _a : (utilsAndConstants_1.defaultGetCacheKey);
72
63
  // @ts-expect-error fix later
73
64
  const cacheKey = getCacheKey(params);
74
- return (0, query_1.query)('query', true, store, cache, queryKey, cacheKey, params);
65
+ return (0, query_1.query)('query', true, store, cache, actions, queryKey, cacheKey, params);
75
66
  },
76
67
  mutate: (options) => {
77
- return (0, mutate_1.mutate)('mutate', true, store, cache, options.mutation, options.params, abortControllers);
68
+ return (0, mutate_1.mutate)('mutate', true, store, cache, actions, options.mutation, options.params, abortControllers);
78
69
  },
79
70
  };
80
71
  return client;
81
72
  }, [store]);
82
73
  },
83
74
  /** Fetches query when params change and subscribes to query state. */
84
- useQuery: (options) => (0, useQuery_1.useQuery)(cache, options),
75
+ useQuery: (options) => (0, useQuery_1.useQuery)(cache, actions, options),
85
76
  /** Subscribes to provided mutation state and provides mutate function. */
86
- useMutation: (options) => (0, useMutation_1.useMutation)(cache, options, abortControllers),
77
+ useMutation: (options) => (0, useMutation_1.useMutation)(cache, actions, options, abortControllers),
87
78
  /** Selects entity by id and subscribes to the changes. */
88
79
  useSelectEntityById: (id, typename) => {
89
- return (0, react_redux_1.useSelector)((state) => id == null ? undefined : cache.cacheStateSelector(state).entities[typename][id]);
80
+ return (0, react_redux_1.useSelector)((state) =>
81
+ // TODO move to selectors?
82
+ id == null ? undefined : cache.cacheStateSelector(state).entities[typename][id]);
90
83
  },
91
84
  },
92
85
  utils: {
package/dist/index.js CHANGED
@@ -29,6 +29,7 @@ Object.defineProperty(exports, "defaultQueryMutationState", { enumerable: true,
29
29
  // try use skip for refreshing strategy?
30
30
  // add example without normalization
31
31
  // make query key / cache key difference more clear in the docs
32
+ // support multiple caches = reducers
32
33
  // ! medium
33
34
  // make named caches to produce named hooks, actions etc (same as slices in RTK)?
34
35
  // allow multiple mutation with same keys?
package/dist/mutate.d.ts CHANGED
@@ -1,3 +1,4 @@
1
1
  import { Store } from 'redux';
2
- import { Cache, Key, MutationResult, Typenames } from './types';
3
- export declare const mutate: <T extends Typenames, QP, QR, MP, MR, MK extends keyof MP | keyof MR>(logTag: string, returnResult: boolean, store: Store, cache: Cache<T, QP, QR, MP, MR>, mutationKey: MK, params: MK extends keyof MP & keyof MR ? MP[MK] : never, abortControllers: WeakMap<Store, Record<Key, AbortController>>) => Promise<void | MutationResult<MK extends keyof MP & keyof MR ? MR[MK] : never>>;
2
+ import type { ActionMap } from './createActions';
3
+ import type { Cache, Key, MutationResult, Typenames } from './types';
4
+ export declare const mutate: <N extends string, T extends Typenames, QP, QR, MP, MR, MK extends keyof MP | keyof MR>(logTag: string, returnResult: boolean, store: Store, cache: Cache<N, T, QP, QR, MP, MR>, { updateMutationStateAndEntities }: Pick<ActionMap<N, T, QR, MR>, "updateMutationStateAndEntities">, mutationKey: MK, params: MK extends keyof MP & keyof MR ? MP[MK] : never, abortControllers: WeakMap<Store, Record<Key, AbortController>>) => Promise<void | MutationResult<MK extends keyof MP & keyof MR ? MR[MK] : never>>;
package/dist/mutate.js CHANGED
@@ -10,9 +10,8 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
10
10
  };
11
11
  Object.defineProperty(exports, "__esModule", { value: true });
12
12
  exports.mutate = void 0;
13
- const actions_1 = require("./actions");
14
13
  const utilsAndConstants_1 = require("./utilsAndConstants");
15
- const mutate = (logTag, returnResult, store, cache, mutationKey, params, abortControllers) => __awaiter(void 0, void 0, void 0, function* () {
14
+ const mutate = (logTag, returnResult, store, cache, { updateMutationStateAndEntities }, mutationKey, params, abortControllers) => __awaiter(void 0, void 0, void 0, function* () {
16
15
  let abortControllersOfStore = abortControllers.get(store);
17
16
  if (abortControllersOfStore === undefined) {
18
17
  abortControllersOfStore = {};
@@ -30,7 +29,7 @@ const mutate = (logTag, returnResult, store, cache, mutationKey, params, abortCo
30
29
  abortController.abort();
31
30
  }
32
31
  else {
33
- store.dispatch((0, actions_1.updateMutationStateAndEntities)(mutationKey, {
32
+ store.dispatch(updateMutationStateAndEntities(mutationKey, {
34
33
  loading: true,
35
34
  result: undefined,
36
35
  }));
@@ -60,14 +59,14 @@ const mutate = (logTag, returnResult, store, cache, mutationKey, params, abortCo
60
59
  }
61
60
  delete abortControllersOfStore[mutationKey];
62
61
  if (error) {
63
- store.dispatch((0, actions_1.updateMutationStateAndEntities)(mutationKey, {
62
+ store.dispatch(updateMutationStateAndEntities(mutationKey, {
64
63
  error: error,
65
64
  loading: false,
66
65
  }));
67
66
  return { error };
68
67
  }
69
68
  if (response) {
70
- store.dispatch((0, actions_1.updateMutationStateAndEntities)(mutationKey, {
69
+ store.dispatch(updateMutationStateAndEntities(mutationKey, {
71
70
  error: undefined,
72
71
  loading: false,
73
72
  // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
package/dist/query.d.ts CHANGED
@@ -1,3 +1,4 @@
1
1
  import { Store } from 'redux';
2
+ import type { ActionMap } from './createActions';
2
3
  import type { Cache, Key, QueryResult, Typenames } from './types';
3
- export declare const query: <T extends Typenames, QP, QR, MP, MR, QK extends keyof QP | keyof QR>(logTag: string, returnResult: boolean, store: Store, cache: Cache<T, QP, QR, MP, MR>, queryKey: QK, cacheKey: Key, params: QK extends keyof QP & keyof QR ? QP[QK] : never) => Promise<void | QueryResult<QK extends keyof QP & keyof QR ? QR[QK] : never>>;
4
+ export declare const query: <N extends string, T extends Typenames, QP, QR, MP, MR, QK extends keyof QP | keyof QR>(logTag: string, returnResult: boolean, store: Store, cache: Cache<N, T, QP, QR, MP, MR>, { updateQueryStateAndEntities }: Pick<ActionMap<N, T, QR, MR>, "updateQueryStateAndEntities">, queryKey: QK, cacheKey: Key, params: QK extends keyof QP & keyof QR ? QP[QK] : never) => Promise<void | QueryResult<QK extends keyof QP & keyof QR ? QR[QK] : never>>;
package/dist/query.js CHANGED
@@ -10,9 +10,8 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
10
10
  };
11
11
  Object.defineProperty(exports, "__esModule", { value: true });
12
12
  exports.query = void 0;
13
- const actions_1 = require("./actions");
14
13
  const utilsAndConstants_1 = require("./utilsAndConstants");
15
- const query = (logTag, returnResult, store, cache, queryKey, cacheKey, params) => __awaiter(void 0, void 0, void 0, function* () {
14
+ const query = (logTag, returnResult, store, cache, { updateQueryStateAndEntities }, queryKey, cacheKey, params) => __awaiter(void 0, void 0, void 0, function* () {
16
15
  var _a;
17
16
  const logsEnabled = cache.options.logsEnabled;
18
17
  const cacheStateSelector = cache.cacheStateSelector;
@@ -28,7 +27,7 @@ const query = (logTag, returnResult, store, cache, queryKey, cacheKey, params) =
28
27
  });
29
28
  return returnResult ? { cancelled: true } : undefined;
30
29
  }
31
- store.dispatch((0, actions_1.updateQueryStateAndEntities)(queryKey, cacheKey, {
30
+ store.dispatch(updateQueryStateAndEntities(queryKey, cacheKey, {
32
31
  loading: true,
33
32
  }));
34
33
  logsEnabled && (0, utilsAndConstants_1.log)(`${logTag} started`, { queryStateOnStart, params, cacheKey });
@@ -40,7 +39,7 @@ const query = (logTag, returnResult, store, cache, queryKey, cacheKey, params) =
40
39
  params);
41
40
  }
42
41
  catch (error) {
43
- store.dispatch((0, actions_1.updateQueryStateAndEntities)(queryKey, cacheKey, {
42
+ store.dispatch(updateQueryStateAndEntities(queryKey, cacheKey, {
44
43
  error: error,
45
44
  loading: false,
46
45
  }));
@@ -57,7 +56,7 @@ const query = (logTag, returnResult, store, cache, queryKey, cacheKey, params) =
57
56
  (_a = cacheStateSelector(store.getState()).queries[queryKey][cacheKey]) === null || _a === void 0 ? void 0 : _a.result, response, params)
58
57
  : response.result,
59
58
  };
60
- store.dispatch((0, actions_1.updateQueryStateAndEntities)(queryKey, cacheKey, newState, response));
59
+ store.dispatch(updateQueryStateAndEntities(queryKey, cacheKey, newState, response));
61
60
  // @ts-expect-error fix types
62
61
  return returnResult
63
62
  ? {
package/dist/reducer.d.ts CHANGED
@@ -1,39 +1,35 @@
1
- import { clearMutationState, clearQueryState, mergeEntityChanges, updateMutationStateAndEntities, updateQueryStateAndEntities } from './actions';
2
- import type { Cache, Dict, EntitiesMap, QueryMutationState, Typenames } from './types';
3
- export type ReduxCacheState<T extends Typenames, QP, QR, MP, MR> = ReturnType<ReturnType<typeof createCacheReducer<T, QP, QR, MP, MR>>>;
4
- export declare const createCacheReducer: <T extends Typenames, QP, QR, MP, MR>(typenames: T, queries: QP & QR extends infer T_1 ? { [QK in keyof T_1]: QK extends keyof QP & keyof QR ? import("./types").QueryInfo<T, QP[QK], QR[QK], {
1
+ import type { ActionMap } from './createActions';
2
+ import type { CacheOptions, Dict, EntitiesMap, QueryMutationState, Typenames } from './types';
3
+ export type ReduxCacheState<T extends Typenames, QR, MR> = ReturnType<ReturnType<typeof createCacheReducer<string, T, QR, MR>>>;
4
+ export declare const createCacheReducer: <N extends string, T extends Typenames, QR, MR>(actions: ActionMap<N, T, QR, MR>, typenames: T, queryKeys: (keyof QR)[], cacheOptions: CacheOptions) => (state: {
5
5
  entities: EntitiesMap<T>;
6
- queries: { [QK_1 in keyof QR]: Dict<QueryMutationState<QR[QK_1]>>; };
7
- mutations: { [MK in keyof MR]: QueryMutationState<MR[MK]>; };
8
- }> : never; } : never, mutations: MP & MR extends infer T_2 ? { [MK_1 in keyof T_2]: MK_1 extends keyof MP & keyof MR ? import("./types").MutationInfo<T, MP[MK_1], MR[MK_1]> : never; } : never, cacheOptions: import("./types").CacheOptions) => (state: {
9
- entities: EntitiesMap<T>;
10
- queries: { [QK_1 in keyof QR]: Dict<QueryMutationState<QR[QK_1]>>; };
6
+ queries: { [QK in keyof QR]: Dict<QueryMutationState<QR[QK]>>; };
11
7
  mutations: { [MK in keyof MR]: QueryMutationState<MR[MK]>; };
12
8
  } | undefined, action: {
13
- type: `${string}UPDATE_QUERY_STATE_AND_ENTITIES`;
9
+ type: `@rrc/${N}/updateQueryStateAndEntities`;
14
10
  queryKey: keyof QR;
15
11
  queryCacheKey: import("./types").Key;
16
12
  state: Partial<QueryMutationState<QR[keyof QR]>> | undefined;
17
13
  entityChagnes: import("./types").EntityChanges<T> | undefined;
18
14
  } | {
19
- type: `${string}UPDATE_MUTATION_STATE_AND_ENTITIES`;
15
+ type: `@rrc/${N}/updateMutationStateAndEntities`;
20
16
  mutationKey: keyof MR;
21
17
  state: Partial<QueryMutationState<MR[keyof MR]>> | undefined;
22
18
  entityChagnes: import("./types").EntityChanges<T> | undefined;
23
19
  } | {
24
- type: `${string}MERGE_ENTITY_CHANGES`;
20
+ type: `@rrc/${N}/mergeEntityChanges`;
25
21
  changes: import("./types").EntityChanges<T>;
26
22
  } | {
27
- type: `${string}CLEAR_QUERY_STATE`;
23
+ type: `@rrc/${N}/clearQueryState`;
28
24
  queryKeys: {
29
25
  key: keyof QR;
30
26
  cacheKey?: import("./types").Key | undefined;
31
27
  }[];
32
28
  } | {
33
- type: `${string}CLEAR_MUTATION_STATE`;
29
+ type: `@rrc/${N}/clearMutationState`;
34
30
  mutationKeys: (keyof MR)[];
35
31
  }) => {
36
32
  entities: EntitiesMap<T>;
37
- queries: { [QK_1 in keyof QR]: Dict<QueryMutationState<QR[QK_1]>>; };
33
+ queries: { [QK in keyof QR]: Dict<QueryMutationState<QR[QK]>>; };
38
34
  mutations: { [MK in keyof MR]: QueryMutationState<MR[MK]>; };
39
35
  };
package/dist/reducer.js CHANGED
@@ -3,59 +3,58 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.createCacheReducer = void 0;
4
4
  const utilsAndConstants_1 = require("./utilsAndConstants");
5
5
  const EMPTY_QUERY_STATE = Object.freeze({});
6
- const createCacheReducer = (typenames, queries, mutations, cacheOptions) => {
6
+ const createCacheReducer = (actions, typenames, queryKeys, cacheOptions) => {
7
7
  const entitiesMap = {};
8
8
  for (const key in typenames) {
9
9
  entitiesMap[key] = EMPTY_QUERY_STATE;
10
10
  }
11
- const queriesMap = {};
12
- for (const key in queries) {
13
- queriesMap[key] = {};
11
+ const queryStateMap = {};
12
+ for (const key of queryKeys) {
13
+ queryStateMap[key] = {};
14
14
  }
15
- const mutationsMap = {};
15
+ const mutationStateMap = {};
16
16
  const initialState = {
17
17
  entities: entitiesMap,
18
- queries: queriesMap,
19
- mutations: mutationsMap,
18
+ queries: queryStateMap,
19
+ mutations: mutationStateMap,
20
20
  };
21
21
  cacheOptions.logsEnabled &&
22
22
  (0, utilsAndConstants_1.log)('createCacheReducer', {
23
23
  typenames,
24
- queries,
25
- mutations,
24
+ queryKeys,
26
25
  initialState,
27
26
  });
28
27
  return (state = initialState, action) => {
29
28
  var _a, _b;
30
29
  switch (action.type) {
31
- case '@RRC/UPDATE_QUERY_STATE_AND_ENTITIES': {
32
- const { queryKey, queryCacheKey, state: queryState, entityChagnes } = action;
30
+ case actions.updateQueryStateAndEntities.type: {
31
+ const { queryKey, queryCacheKey, state: queryState, entityChagnes, } = action;
33
32
  const newEntities = entityChagnes && (0, utilsAndConstants_1.applyEntityChanges)(state.entities, entityChagnes, cacheOptions);
34
33
  if (!queryState && !newEntities) {
35
34
  return state;
36
35
  }
37
36
  return Object.assign(Object.assign(Object.assign({}, state), (newEntities ? { entities: newEntities } : null)), { queries: Object.assign(Object.assign({}, state.queries), { [queryKey]: Object.assign(Object.assign({}, state.queries[queryKey]), { [queryCacheKey]: Object.assign(Object.assign({}, ((_a = state.queries[queryKey][queryCacheKey]) !== null && _a !== void 0 ? _a : utilsAndConstants_1.DEFAULT_QUERY_MUTATION_STATE)), queryState) }) }) });
38
37
  }
39
- case '@RRC/UPDATE_MUTATION_STATE_AND_ENTITIES': {
40
- const { mutationKey, state: mutationState, entityChagnes } = action;
38
+ case actions.updateMutationStateAndEntities.type: {
39
+ const { mutationKey, state: mutationState, entityChagnes, } = action;
41
40
  const newEntities = entityChagnes && (0, utilsAndConstants_1.applyEntityChanges)(state.entities, entityChagnes, cacheOptions);
42
41
  if (!mutationState && !newEntities) {
43
42
  return state;
44
43
  }
45
44
  return Object.assign(Object.assign(Object.assign({}, state), (newEntities ? { entities: newEntities } : null)), { mutations: Object.assign(Object.assign({}, state.mutations), { [mutationKey]: Object.assign(Object.assign({}, ((_b = state.mutations[mutationKey]) !== null && _b !== void 0 ? _b : utilsAndConstants_1.DEFAULT_QUERY_MUTATION_STATE)), mutationState) }) });
46
45
  }
47
- case '@RRC/MERGE_ENTITY_CHANGES': {
46
+ case actions.mergeEntityChanges.type: {
48
47
  const { changes } = action;
49
48
  const newEntities = (0, utilsAndConstants_1.applyEntityChanges)(state.entities, changes, cacheOptions);
50
49
  return newEntities ? Object.assign(Object.assign({}, state), { entities: newEntities }) : state;
51
50
  }
52
- case '@RRC/CLEAR_QUERY_STATE': {
53
- const { queryKeys } = action;
54
- if (!queryKeys.length) {
51
+ case actions.clearQueryState.type: {
52
+ const { queryKeys: queryKeysToClear } = action;
53
+ if (!queryKeysToClear.length) {
55
54
  return state;
56
55
  }
57
56
  let newQueries = undefined;
58
- for (const query of queryKeys) {
57
+ for (const query of queryKeysToClear) {
59
58
  if (query.cacheKey != null) {
60
59
  if ((newQueries !== null && newQueries !== void 0 ? newQueries : state.queries)[query.key][query.cacheKey]) {
61
60
  newQueries !== null && newQueries !== void 0 ? newQueries : (newQueries = Object.assign({}, state.queries));
@@ -73,7 +72,7 @@ const createCacheReducer = (typenames, queries, mutations, cacheOptions) => {
73
72
  }
74
73
  return Object.assign(Object.assign({}, state), { queries: newQueries });
75
74
  }
76
- case '@RRC/CLEAR_MUTATION_STATE': {
75
+ case actions.clearMutationState.type: {
77
76
  const { mutationKeys } = action;
78
77
  if (!mutationKeys.length) {
79
78
  return state;
package/dist/types.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { createCacheReducer, ReduxCacheState } from './reducer';
1
+ import type { ReduxCacheState } from './reducer';
2
2
  export type Key = string | number | symbol;
3
3
  export type Dict<T> = Record<Key, T>;
4
4
  export type OptionalPartial<T, K extends keyof T> = Partial<{
@@ -17,17 +17,26 @@ export type EntityChanges<T extends Typenames> = {
17
17
  };
18
18
  /** Record of typename and its corresponding entity type */
19
19
  export type Typenames = Record<string, object>;
20
- export type Cache<T extends Typenames, QP, QR, MP, MR> = {
20
+ export type Cache<N extends string, T extends Typenames, QP, QR, MP, MR> = {
21
+ /** Used as prefix for actions and in default cacheStateSelector for selecting cache state from redux state. */
22
+ name: N;
23
+ /** Mapping of all typenames to their entity types, which is needed for proper typing and normalization.
24
+ * Empty objects with type casting can be used as values.
25
+ * @example
26
+ * typenames: {
27
+ users: {} as User, // here `users` entities will have type `User`
28
+ banks: {} as Bank,
29
+ } */
21
30
  typenames: T;
22
31
  queries: {
23
- [QK in keyof (QP & QR)]: QK extends keyof (QP | QR) ? QueryInfo<T, QP[QK], QR[QK], ReturnType<ReturnType<typeof createCacheReducer<T, QP, QR, MP, MR>>>> : never;
32
+ [QK in keyof (QP & QR)]: QK extends keyof (QP | QR) ? QueryInfo<T, QP[QK], QR[QK], ReduxCacheState<T, QR, MR>> : never;
24
33
  };
25
34
  mutations: {
26
35
  [MK in keyof (MP & MR)]: MK extends keyof (MP | MR) ? MutationInfo<T, MP[MK], MR[MK]> : never;
27
36
  };
28
37
  options: CacheOptions;
29
- /** Returns cache state from redux root state. */
30
- cacheStateSelector: (state: any) => ReduxCacheState<T, QP, QR, MP, MR>;
38
+ /** Should return cache state from redux root state. Default implementation returns `state[name]`. */
39
+ cacheStateSelector: (state: any) => ReduxCacheState<T, QR, MR>;
31
40
  };
32
41
  export type CacheOptions = {
33
42
  /**
@@ -73,11 +82,11 @@ export type QueryInfo<T extends Typenames, P, R, S> = {
73
82
  * */
74
83
  getCacheKey?: (params?: P) => Key;
75
84
  };
76
- export type UseQueryOptions<T extends Typenames, QP, QR, MP, MR, QK extends keyof (QP & QR)> = {
85
+ export type UseQueryOptions<T extends Typenames, QP, QR, MR, QK extends keyof (QP & QR)> = {
77
86
  query: QK;
78
87
  params: QK extends keyof (QP | QR) ? QP[QK] : never;
79
88
  skip?: boolean;
80
- } & Pick<QK extends keyof (QP | QR) ? QueryInfo<T, QP[QK], QR[QK], ReduxCacheState<T, QP, QR, MP, MR>> : never, 'cachePolicy' | 'mergeResults' | 'getCacheKey'>;
89
+ } & Pick<QK extends keyof (QP | QR) ? QueryInfo<T, QP[QK], QR[QK], ReduxCacheState<T, QR, MR>> : never, 'cachePolicy' | 'mergeResults' | 'getCacheKey'>;
81
90
  /**
82
91
  * @param cache-first for each params key fetch is not called if cache exists.
83
92
  * @param cache-and-fetch for each params key result is taken from cache and fetch is called.
@@ -92,7 +101,7 @@ export type QueryResult<R> = {
92
101
  cancelled?: true;
93
102
  result?: R;
94
103
  };
95
- export type QueryOptions<T extends Typenames, QP, QR, MP, MR, QK extends keyof (QP & QR)> = Omit<UseQueryOptions<T, QP, QR, MP, MR, QK>, 'skip'>;
104
+ export type QueryOptions<T extends Typenames, QP, QR, MR, QK extends keyof (QP & QR)> = Omit<UseQueryOptions<T, QP, QR, MR, QK>, 'skip'>;
96
105
  export type Mutation<T extends Typenames, P, R> = (params: P,
97
106
  /** Signal is aborted for current mutation when the same mutation was called once again. */
98
107
  abortSignal: AbortSignal) => Promise<MutationResponse<T, R>>;
@@ -1,5 +1,6 @@
1
1
  import { Store } from 'redux';
2
+ import { ActionMap } from './createActions';
2
3
  import { Cache, Key, QueryMutationState, Typenames } from './types';
3
- export declare const useMutation: <T extends Typenames, MP, MR, MK extends keyof MP | keyof MR>(cache: Cache<T, unknown, unknown, MP, MR>, options: {
4
+ export declare const useMutation: <N extends string, T extends Typenames, MP, MR, MK extends keyof MP | keyof MR>(cache: Cache<N, T, unknown, unknown, MP, MR>, actions: Pick<ActionMap<N, T, unknown, MR>, "updateMutationStateAndEntities">, options: {
4
5
  mutation: MK;
5
6
  }, abortControllers: WeakMap<Store, Record<Key, AbortController>>) => readonly [(params: MK extends keyof MP & keyof MR ? MP[MK] : never) => Promise<void>, QueryMutationState<MK extends keyof MP & keyof MR ? MP[MK] : never>, () => boolean];
@@ -12,10 +12,9 @@ Object.defineProperty(exports, "__esModule", { value: true });
12
12
  exports.useMutation = void 0;
13
13
  const react_1 = require("react");
14
14
  const react_redux_1 = require("react-redux");
15
- const actions_1 = require("./actions");
16
15
  const mutate_1 = require("./mutate");
17
16
  const utilsAndConstants_1 = require("./utilsAndConstants");
18
- const useMutation = (cache, options, abortControllers) => {
17
+ const useMutation = (cache, actions, options, abortControllers) => {
19
18
  var _a;
20
19
  const { mutation: mutationKey } = options;
21
20
  const store = (0, react_redux_1.useStore)();
@@ -33,7 +32,7 @@ const useMutation = (cache, options, abortControllers) => {
33
32
  },
34
33
  // mutate
35
34
  (params) => __awaiter(void 0, void 0, void 0, function* () {
36
- yield (0, mutate_1.mutate)('useMutation.mutate', false, store, cache, mutationKey, params, abortControllers);
35
+ yield (0, mutate_1.mutate)('useMutation.mutate', false, store, cache, actions, mutationKey, params, abortControllers);
37
36
  }),
38
37
  // abort
39
38
  () => {
@@ -43,7 +42,7 @@ const useMutation = (cache, options, abortControllers) => {
43
42
  return false;
44
43
  }
45
44
  abortController.abort();
46
- store.dispatch((0, actions_1.updateMutationStateAndEntities)(mutationKey, {
45
+ store.dispatch(actions.updateMutationStateAndEntities(mutationKey, {
47
46
  loading: false,
48
47
  }));
49
48
  return true;
@@ -1,2 +1,3 @@
1
+ import { ActionMap } from './createActions';
1
2
  import { Cache, QueryMutationState, Typenames, UseQueryOptions } from './types';
2
- export declare const useQuery: <T extends Typenames, QP, QR, MP, MR, QK extends keyof QP | keyof QR>(cache: Cache<T, QP, QR, MP, MR>, options: UseQueryOptions<T, QP, QR, MP, MR, QK>) => readonly [QueryMutationState<QK extends keyof QP & keyof QR ? QR[QK] : never>, () => Promise<void>];
3
+ export declare const useQuery: <N extends string, T extends Typenames, QP, QR, MP, MR, QK extends keyof QP | keyof QR>(cache: Cache<N, T, QP, QR, MP, MR>, actions: Pick<ActionMap<N, T, QR, MR>, "updateQueryStateAndEntities">, options: UseQueryOptions<T, QP, QR, MR, QK>) => readonly [QueryMutationState<QK extends keyof QP & keyof QR ? QR[QK] : never>, () => Promise<void>];
package/dist/useQuery.js CHANGED
@@ -14,7 +14,7 @@ const react_1 = require("react");
14
14
  const react_redux_1 = require("react-redux");
15
15
  const query_1 = require("./query");
16
16
  const utilsAndConstants_1 = require("./utilsAndConstants");
17
- const useQuery = (cache, options) => {
17
+ const useQuery = (cache, actions, options) => {
18
18
  var _a, _b, _c;
19
19
  const { query: queryKey, skip, params, cachePolicy = (_a = cache.queries[queryKey].cachePolicy) !== null && _a !== void 0 ? _a : 'cache-first', getCacheKey = (_b = cache.queries[queryKey].getCacheKey) !== null && _b !== void 0 ? _b : (utilsAndConstants_1.defaultGetCacheKey), } = options;
20
20
  const logsEnabled = cache.options.logsEnabled;
@@ -34,7 +34,7 @@ const useQuery = (cache, options) => {
34
34
  const resultFromSelector = (resultSelector && (0, react_redux_1.useSelector)(resultSelector));
35
35
  const hasResultFromSelector = resultFromSelector !== undefined;
36
36
  const fetch = (0, react_1.useCallback)(() => __awaiter(void 0, void 0, void 0, function* () {
37
- yield (0, query_1.query)('useQuery.fetch', false, store, cache, queryKey, cacheKey, params);
37
+ yield (0, query_1.query)('useQuery.fetch', false, store, cache, actions, queryKey, cacheKey, params);
38
38
  // eslint-disable-next-line react-hooks/exhaustive-deps
39
39
  }), [store, queryKey, cacheKey]);
40
40
  const queryStateFromSelector = (_c = (0, react_redux_1.useSelector)((state) => {
@@ -1,5 +1,5 @@
1
1
  import type { CacheOptions, EntitiesMap, EntityChanges, Key, Typenames } from './types';
2
- export declare const PACKAGE_SHORT_NAME = "RRC";
2
+ export declare const PACKAGE_SHORT_NAME = "rrc";
3
3
  export declare const IS_DEV: boolean;
4
4
  export declare const DEFAULT_QUERY_MUTATION_STATE: {
5
5
  readonly loading: false;
@@ -1,7 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.applyEntityChanges = exports.log = exports.defaultGetCacheKey = exports.DEFAULT_QUERY_MUTATION_STATE = exports.IS_DEV = exports.PACKAGE_SHORT_NAME = void 0;
4
- exports.PACKAGE_SHORT_NAME = 'RRC';
4
+ exports.PACKAGE_SHORT_NAME = 'rrc';
5
5
  exports.IS_DEV = (() => {
6
6
  try {
7
7
  // @ts-expect-error __DEV__ is only for React Native
package/package.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "name": "react-redux-cache",
3
3
  "author": "Alexander Danilov",
4
4
  "license": "MIT",
5
- "version": "0.1.1",
5
+ "version": "0.2.0",
6
6
  "description": "Powerful data fetching and caching library that supports normalization, built on top of redux",
7
7
  "main": "dist/index.js",
8
8
  "types": "dist/index.d.ts",
@@ -38,7 +38,7 @@
38
38
  "redux": "4.2.1",
39
39
  "redux-logger": "3.0.6",
40
40
  "ts-jest": "29.1.0",
41
- "typescript": "5.0.4"
41
+ "typescript": "5.0"
42
42
  },
43
43
  "peerDependencies": {
44
44
  "react": "^16",
package/dist/actions.d.ts DELETED
@@ -1,32 +0,0 @@
1
- import type { EntityChanges, Key, QueryMutationState, Typenames } from './types';
2
- export declare const updateQueryStateAndEntities: <T extends Typenames, QR, K extends keyof QR>(queryKey: K, queryCacheKey: Key, state?: Partial<QueryMutationState<QR[K]>> | undefined, entityChagnes?: EntityChanges<T> | undefined) => {
3
- type: `${string}UPDATE_QUERY_STATE_AND_ENTITIES`;
4
- queryKey: K;
5
- queryCacheKey: Key;
6
- state: Partial<QueryMutationState<QR[K]>> | undefined;
7
- entityChagnes: EntityChanges<T> | undefined;
8
- };
9
- export declare const updateMutationStateAndEntities: <T extends Typenames, MR, K extends keyof MR>(mutationKey: K, state?: Partial<QueryMutationState<MR[K]>> | undefined, entityChagnes?: EntityChanges<T> | undefined) => {
10
- type: `${string}UPDATE_MUTATION_STATE_AND_ENTITIES`;
11
- mutationKey: K;
12
- state: Partial<QueryMutationState<MR[K]>> | undefined;
13
- entityChagnes: EntityChanges<T> | undefined;
14
- };
15
- export declare const mergeEntityChanges: <T extends Typenames>(changes: EntityChanges<T>) => {
16
- type: `${string}MERGE_ENTITY_CHANGES`;
17
- changes: EntityChanges<T>;
18
- };
19
- export declare const clearQueryState: <QR, K extends keyof QR>(queryKeys: {
20
- key: K;
21
- cacheKey?: Key | undefined;
22
- }[]) => {
23
- type: `${string}CLEAR_QUERY_STATE`;
24
- queryKeys: {
25
- key: K;
26
- cacheKey?: Key | undefined;
27
- }[];
28
- };
29
- export declare const clearMutationState: <MR, K extends keyof MR>(mutationKeys: K[]) => {
30
- type: `${string}CLEAR_MUTATION_STATE`;
31
- mutationKeys: K[];
32
- };
package/dist/actions.js DELETED
@@ -1,35 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.clearMutationState = exports.clearQueryState = exports.mergeEntityChanges = exports.updateMutationStateAndEntities = exports.updateQueryStateAndEntities = void 0;
4
- const utilsAndConstants_1 = require("./utilsAndConstants");
5
- const ACTION_PREFIX = `@${utilsAndConstants_1.PACKAGE_SHORT_NAME}/`;
6
- const updateQueryStateAndEntities = (queryKey, queryCacheKey, state, entityChagnes) => ({
7
- type: `${ACTION_PREFIX}UPDATE_QUERY_STATE_AND_ENTITIES`,
8
- queryKey,
9
- queryCacheKey,
10
- state,
11
- entityChagnes,
12
- });
13
- exports.updateQueryStateAndEntities = updateQueryStateAndEntities;
14
- const updateMutationStateAndEntities = (mutationKey, state, entityChagnes) => ({
15
- type: `${ACTION_PREFIX}UPDATE_MUTATION_STATE_AND_ENTITIES`,
16
- mutationKey,
17
- state,
18
- entityChagnes,
19
- });
20
- exports.updateMutationStateAndEntities = updateMutationStateAndEntities;
21
- const mergeEntityChanges = (changes) => ({
22
- type: `${ACTION_PREFIX}MERGE_ENTITY_CHANGES`,
23
- changes,
24
- });
25
- exports.mergeEntityChanges = mergeEntityChanges;
26
- const clearQueryState = (queryKeys) => ({
27
- type: `${ACTION_PREFIX}CLEAR_QUERY_STATE`,
28
- queryKeys,
29
- });
30
- exports.clearQueryState = clearQueryState;
31
- const clearMutationState = (mutationKeys) => ({
32
- type: `${ACTION_PREFIX}CLEAR_MUTATION_STATE`,
33
- mutationKeys,
34
- });
35
- exports.clearMutationState = clearMutationState;