UNPKG

13 kBTypeScriptView Raw
1/**
2 * Note: this file should import all other files for type discovery and declaration merging
3 */
4import type { PatchQueryDataThunk, UpdateQueryDataThunk } from './buildThunks';
5import './buildThunks';
6import type { ActionCreatorWithPayload, AnyAction, Middleware, Reducer, ThunkAction, ThunkDispatch } from '@reduxjs/toolkit';
7import type { EndpointDefinitions, QueryArgFrom, QueryDefinition, MutationDefinition, FullTagDescription } from '../endpointDefinitions';
8import type { CombinedState, QueryKeys, RootState } from './apiState';
9import type { Module } from '../apiTypes';
10import { onFocus, onFocusLost, onOnline, onOffline } from './setupListeners';
11import './buildSelectors';
12import './buildInitiate';
13import type { SliceActions } from './buildSlice';
14import type { BaseQueryFn } from '../baseQueryTypes';
15import type { ReferenceCacheLifecycle } from './buildMiddleware/cacheLifecycle';
16import type { ReferenceQueryLifecycle } from './buildMiddleware/queryLifecycle';
17import type { ReferenceCacheCollection } from './buildMiddleware/cacheCollection';
18/**
19 * `ifOlderThan` - (default: `false` | `number`) - _number is value in seconds_
20 * - If specified, it will only run the query if the difference between `new Date()` and the last `fulfilledTimeStamp` is greater than the given value
21 *
22 * @overloadSummary
23 * `force`
24 * - If `force: true`, it will ignore the `ifOlderThan` value if it is set and the query will be run even if it exists in the cache.
25 */
26export declare type PrefetchOptions = {
27 ifOlderThan?: false | number;
28} | {
29 force?: boolean;
30};
31export declare const coreModuleName: unique symbol;
32export declare type CoreModule = typeof coreModuleName | ReferenceCacheLifecycle | ReferenceQueryLifecycle | ReferenceCacheCollection;
33declare module '../apiTypes' {
34 interface ApiModules<BaseQuery extends BaseQueryFn, Definitions extends EndpointDefinitions, ReducerPath extends string, TagTypes extends string> {
35 [coreModuleName]: {
36 /**
37 * This api's reducer should be mounted at `store[api.reducerPath]`.
38 *
39 * @example
40 * ```ts
41 * configureStore({
42 * reducer: {
43 * [api.reducerPath]: api.reducer,
44 * },
45 * middleware: (getDefaultMiddleware) => getDefaultMiddleware().concat(api.middleware),
46 * })
47 * ```
48 */
49 reducerPath: ReducerPath;
50 /**
51 * Internal actions not part of the public API. Note: These are subject to change at any given time.
52 */
53 internalActions: InternalActions;
54 /**
55 * A standard redux reducer that enables core functionality. Make sure it's included in your store.
56 *
57 * @example
58 * ```ts
59 * configureStore({
60 * reducer: {
61 * [api.reducerPath]: api.reducer,
62 * },
63 * middleware: (getDefaultMiddleware) => getDefaultMiddleware().concat(api.middleware),
64 * })
65 * ```
66 */
67 reducer: Reducer<CombinedState<Definitions, TagTypes, ReducerPath>, AnyAction>;
68 /**
69 * This is a standard redux middleware and is responsible for things like polling, garbage collection and a handful of other things. Make sure it's included in your store.
70 *
71 * @example
72 * ```ts
73 * configureStore({
74 * reducer: {
75 * [api.reducerPath]: api.reducer,
76 * },
77 * middleware: (getDefaultMiddleware) => getDefaultMiddleware().concat(api.middleware),
78 * })
79 * ```
80 */
81 middleware: Middleware<{}, RootState<Definitions, string, ReducerPath>, ThunkDispatch<any, any, AnyAction>>;
82 /**
83 * A collection of utility thunks for various situations.
84 */
85 util: {
86 /**
87 * A Redux thunk that can be used to manually trigger pre-fetching of data.
88 *
89 * The thunk accepts three arguments: the name of the endpoint we are updating (such as `'getPost'`), any relevant query arguments, and a set of options used to determine if the data actually should be re-fetched based on cache staleness.
90 *
91 * React Hooks users will most likely never need to use this directly, as the `usePrefetch` hook will dispatch this thunk internally as needed when you call the prefetching function supplied by the hook.
92 *
93 * @example
94 *
95 * ```ts no-transpile
96 * dispatch(api.util.prefetch('getPosts', undefined, { force: true }))
97 * ```
98 */
99 prefetch<EndpointName extends QueryKeys<Definitions>>(endpointName: EndpointName, arg: QueryArgFrom<Definitions[EndpointName]>, options: PrefetchOptions): ThunkAction<void, any, any, AnyAction>;
100 /**
101 * A Redux thunk action creator that, when dispatched, creates and applies a set of JSON diff/patch objects to the current state. This immediately updates the Redux state with those changes.
102 *
103 * The thunk action creator accepts three arguments: the name of the endpoint we are updating (such as `'getPost'`), any relevant query arguments, and a callback function. The callback receives an Immer-wrapped `draft` of the current state, and may modify the draft to match the expected results after the mutation completes successfully.
104 *
105 * The thunk returns an object containing `{patches: Patch[], inversePatches: Patch[], undo: () => void}`. The `patches` and `inversePatches` are generated using Immer's [`produceWithPatches` method](https://immerjs.github.io/immer/patches).
106 *
107 * This is typically used as the first step in implementing optimistic updates. The generated `inversePatches` can be used to revert the updates by calling `dispatch(patchQueryData(endpointName, args, inversePatches))`. Alternatively, the `undo` method can be called directly to achieve the same effect.
108 *
109 * @example
110 *
111 * ```ts
112 * const patchCollection = dispatch(
113 * api.util.updateQueryData('getPosts', undefined, (draftPosts) => {
114 * draftPosts.push({ id: 1, name: 'Teddy' })
115 * })
116 * )
117 * ```
118 */
119 updateQueryData: UpdateQueryDataThunk<Definitions, RootState<Definitions, string, ReducerPath>>;
120 /** @deprecated renamed to `updateQueryData` */
121 updateQueryResult: UpdateQueryDataThunk<Definitions, RootState<Definitions, string, ReducerPath>>;
122 /**
123 * A Redux thunk that applies a JSON diff/patch array to the cached data for a given query result. This immediately updates the Redux state with those changes.
124 *
125 * The thunk accepts three arguments: the name of the endpoint we are updating (such as `'getPost'`), any relevant query arguments, and a JSON diff/patch array as produced by Immer's `produceWithPatches`.
126 *
127 * This is typically used as the second step in implementing optimistic updates. If a request fails, the optimistically-applied changes can be reverted by dispatching `patchQueryData` with the `inversePatches` that were generated by `updateQueryData` earlier.
128 *
129 * In cases where it is desired to simply revert the previous changes, it may be preferable to call the `undo` method returned from dispatching `updateQueryData` instead.
130 *
131 * @example
132 * ```ts
133 * const patchCollection = dispatch(
134 * api.util.updateQueryData('getPosts', undefined, (draftPosts) => {
135 * draftPosts.push({ id: 1, name: 'Teddy' })
136 * })
137 * )
138 *
139 * // later
140 * dispatch(
141 * api.util.patchQueryData('getPosts', undefined, patchCollection.inversePatches)
142 * )
143 *
144 * // or
145 * patchCollection.undo()
146 * ```
147 */
148 patchQueryData: PatchQueryDataThunk<Definitions, RootState<Definitions, string, ReducerPath>>;
149 /** @deprecated renamed to `patchQueryData` */
150 patchQueryResult: PatchQueryDataThunk<Definitions, RootState<Definitions, string, ReducerPath>>;
151 /**
152 * A Redux action creator that can be dispatched to manually reset the api state completely. This will immediately remove all existing cache entries, and all queries will be considered 'uninitialized'.
153 *
154 * @example
155 *
156 * ```ts
157 * dispatch(api.util.resetApiState())
158 * ```
159 */
160 resetApiState: SliceActions['resetApiState'];
161 /**
162 * A Redux action creator that can be used to manually invalidate cache tags for [automated re-fetching](../../usage/automated-refetching.mdx).
163 *
164 * The action creator accepts one argument: the cache tags to be invalidated. It returns an action with those tags as a payload, and the corresponding `invalidateTags` action type for the api.
165 *
166 * Dispatching the result of this action creator will [invalidate](../../usage/automated-refetching.mdx#invalidating-cache-data) the given tags, causing queries to automatically re-fetch if they are subscribed to cache data that [provides](../../usage/automated-refetching.mdx#providing-cache-data) the corresponding tags.
167 *
168 * The array of tags provided to the action creator should be in one of the following formats, where `TagType` is equal to a string provided to the [`tagTypes`](../createApi.mdx#tagtypes) property of the api:
169 *
170 * - `[TagType]`
171 * - `[{ type: TagType }]`
172 * - `[{ type: TagType, id: number | string }]`
173 *
174 * @example
175 *
176 * ```ts
177 * dispatch(api.util.invalidateTags(['Post']))
178 * dispatch(api.util.invalidateTags([{ type: 'Post', id: 1 }]))
179 * dispatch(
180 * api.util.invalidateTags([
181 * { type: 'Post', id: 1 },
182 * { type: 'Post', id: 'LIST' },
183 * ])
184 * )
185 * ```
186 */
187 invalidateTags: ActionCreatorWithPayload<Array<TagTypes | FullTagDescription<TagTypes>>, string>;
188 };
189 /**
190 * Endpoints based on the input endpoints provided to `createApi`, containing `select` and `action matchers`.
191 */
192 endpoints: {
193 [K in keyof Definitions]: Definitions[K] extends QueryDefinition<any, any, any, any, any> ? ApiEndpointQuery<Definitions[K], Definitions> : Definitions[K] extends MutationDefinition<any, any, any, any, any> ? ApiEndpointMutation<Definitions[K], Definitions> : never;
194 };
195 };
196 }
197}
198export interface ApiEndpointQuery<Definition extends QueryDefinition<any, any, any, any, any>, Definitions extends EndpointDefinitions> {
199}
200export interface ApiEndpointMutation<Definition extends MutationDefinition<any, any, any, any, any>, Definitions extends EndpointDefinitions> {
201}
202export declare type ListenerActions = {
203 /**
204 * Will cause the RTK Query middleware to trigger any refetchOnReconnect-related behavior
205 * @link https://rtk-query-docs.netlify.app/api/setupListeners
206 */
207 onOnline: typeof onOnline;
208 onOffline: typeof onOffline;
209 /**
210 * Will cause the RTK Query middleware to trigger any refetchOnFocus-related behavior
211 * @link https://rtk-query-docs.netlify.app/api/setupListeners
212 */
213 onFocus: typeof onFocus;
214 onFocusLost: typeof onFocusLost;
215};
216export declare type InternalActions = SliceActions & ListenerActions;
217/**
218 * Creates a module containing the basic redux logic for use with `buildCreateApi`.
219 *
220 * @example
221 * ```ts
222 * const createBaseApi = buildCreateApi(coreModule());
223 * ```
224 */
225export declare const coreModule: () => Module<CoreModule>;