UNPKG

20.2 kBTypeScriptView Raw
1/**
2 * Note: this file should import all other files for type discovery and declaration merging
3 */
4import type { PatchQueryDataThunk, UpdateQueryDataThunk, UpsertQueryDataThunk } from './buildThunks';
5import './buildThunks';
6import type { ActionCreatorWithPayload, AnyAction, Middleware, Reducer, ThunkAction, ThunkDispatch } from '@reduxjs/toolkit';
7import type { EndpointDefinitions, QueryArgFrom, QueryDefinition, MutationDefinition, TagDescription } from '../endpointDefinitions';
8import type { CombinedState, QueryKeys, MutationKeys, RootState } from './apiState';
9import type { Module } from '../apiTypes';
10import { onFocus, onFocusLost, onOnline, onOffline } from './setupListeners';
11import './buildSelectors';
12import type { MutationActionCreatorResult, QueryActionCreatorResult } from './buildInitiate';
13import './buildInitiate';
14import type { SliceActions } from './buildSlice';
15import type { BaseQueryFn } from '../baseQueryTypes';
16import type { ReferenceCacheLifecycle } from './buildMiddleware/cacheLifecycle';
17import type { ReferenceQueryLifecycle } from './buildMiddleware/queryLifecycle';
18import type { ReferenceCacheCollection } from './buildMiddleware/cacheCollection';
19/**
20 * `ifOlderThan` - (default: `false` | `number`) - _number is value in seconds_
21 * - If specified, it will only run the query if the difference between `new Date()` and the last `fulfilledTimeStamp` is greater than the given value
22 *
23 * @overloadSummary
24 * `force`
25 * - 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.
26 */
27export declare type PrefetchOptions = {
28 ifOlderThan?: false | number;
29} | {
30 force?: boolean;
31};
32export declare const coreModuleName: unique symbol;
33export declare type CoreModule = typeof coreModuleName | ReferenceCacheLifecycle | ReferenceQueryLifecycle | ReferenceCacheCollection;
34export interface ThunkWithReturnValue<T> extends ThunkAction<T, any, any, AnyAction> {
35}
36declare module '../apiTypes' {
37 interface ApiModules<BaseQuery extends BaseQueryFn, Definitions extends EndpointDefinitions, ReducerPath extends string, TagTypes extends string> {
38 [coreModuleName]: {
39 /**
40 * This api's reducer should be mounted at `store[api.reducerPath]`.
41 *
42 * @example
43 * ```ts
44 * configureStore({
45 * reducer: {
46 * [api.reducerPath]: api.reducer,
47 * },
48 * middleware: (getDefaultMiddleware) => getDefaultMiddleware().concat(api.middleware),
49 * })
50 * ```
51 */
52 reducerPath: ReducerPath;
53 /**
54 * Internal actions not part of the public API. Note: These are subject to change at any given time.
55 */
56 internalActions: InternalActions;
57 /**
58 * A standard redux reducer that enables core functionality. Make sure it's included in your store.
59 *
60 * @example
61 * ```ts
62 * configureStore({
63 * reducer: {
64 * [api.reducerPath]: api.reducer,
65 * },
66 * middleware: (getDefaultMiddleware) => getDefaultMiddleware().concat(api.middleware),
67 * })
68 * ```
69 */
70 reducer: Reducer<CombinedState<Definitions, TagTypes, ReducerPath>, AnyAction>;
71 /**
72 * 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.
73 *
74 * @example
75 * ```ts
76 * configureStore({
77 * reducer: {
78 * [api.reducerPath]: api.reducer,
79 * },
80 * middleware: (getDefaultMiddleware) => getDefaultMiddleware().concat(api.middleware),
81 * })
82 * ```
83 */
84 middleware: Middleware<{}, RootState<Definitions, string, ReducerPath>, ThunkDispatch<any, any, AnyAction>>;
85 /**
86 * A collection of utility thunks for various situations.
87 */
88 util: {
89 /**
90 * This method had to be removed due to a conceptual bug in RTK.
91 *
92 * Despite TypeScript errors, it will continue working in the "buggy" way it did
93 * before in production builds and will be removed in the next major release.
94 *
95 * Nonetheless, you should immediately replace it with the new recommended approach.
96 * See https://redux-toolkit.js.org/rtk-query/usage/server-side-rendering for new guidance on SSR.
97 *
98 * Please see https://github.com/reduxjs/redux-toolkit/pull/2481 for details.
99 * @deprecated
100 */
101 getRunningOperationPromises: never;
102 /**
103 * This method had to be removed due to a conceptual bug in RTK.
104 * It has been replaced by `api.util.getRunningQueryThunk` and `api.util.getRunningMutationThunk`.
105 * Please see https://github.com/reduxjs/redux-toolkit/pull/2481 for details.
106 * @deprecated
107 */
108 getRunningOperationPromise: never;
109 /**
110 * A thunk that (if dispatched) will return a specific running query, identified
111 * by `endpointName` and `args`.
112 * If that query is not running, dispatching the thunk will result in `undefined`.
113 *
114 * Can be used to await a specific query triggered in any way,
115 * including via hook calls or manually dispatching `initiate` actions.
116 *
117 * See https://redux-toolkit.js.org/rtk-query/usage/server-side-rendering for details.
118 */
119 getRunningQueryThunk<EndpointName extends QueryKeys<Definitions>>(endpointName: EndpointName, args: QueryArgFrom<Definitions[EndpointName]>): ThunkWithReturnValue<QueryActionCreatorResult<Definitions[EndpointName] & {
120 type: 'query';
121 }> | undefined>;
122 /**
123 * A thunk that (if dispatched) will return a specific running mutation, identified
124 * by `endpointName` and `fixedCacheKey` or `requestId`.
125 * If that mutation is not running, dispatching the thunk will result in `undefined`.
126 *
127 * Can be used to await a specific mutation triggered in any way,
128 * including via hook trigger functions or manually dispatching `initiate` actions.
129 *
130 * See https://redux-toolkit.js.org/rtk-query/usage/server-side-rendering for details.
131 */
132 getRunningMutationThunk<EndpointName extends MutationKeys<Definitions>>(endpointName: EndpointName, fixedCacheKeyOrRequestId: string): ThunkWithReturnValue<MutationActionCreatorResult<Definitions[EndpointName] & {
133 type: 'mutation';
134 }> | undefined>;
135 /**
136 * A thunk that (if dispatched) will return all running queries.
137 *
138 * Useful for SSR scenarios to await all running queries triggered in any way,
139 * including via hook calls or manually dispatching `initiate` actions.
140 *
141 * See https://redux-toolkit.js.org/rtk-query/usage/server-side-rendering for details.
142 */
143 getRunningQueriesThunk(): ThunkWithReturnValue<Array<QueryActionCreatorResult<any>>>;
144 /**
145 * A thunk that (if dispatched) will return all running mutations.
146 *
147 * Useful for SSR scenarios to await all running mutations triggered in any way,
148 * including via hook calls or manually dispatching `initiate` actions.
149 *
150 * See https://redux-toolkit.js.org/rtk-query/usage/server-side-rendering for details.
151 */
152 getRunningMutationsThunk(): ThunkWithReturnValue<Array<MutationActionCreatorResult<any>>>;
153 /**
154 * A Redux thunk that can be used to manually trigger pre-fetching of data.
155 *
156 * The thunk accepts three arguments: the name of the endpoint we are updating (such as `'getPost'`), the appropriate query arg values to construct the desired cache key, and a set of options used to determine if the data actually should be re-fetched based on cache staleness.
157 *
158 * 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.
159 *
160 * @example
161 *
162 * ```ts no-transpile
163 * dispatch(api.util.prefetch('getPosts', undefined, { force: true }))
164 * ```
165 */
166 prefetch<EndpointName extends QueryKeys<Definitions>>(endpointName: EndpointName, arg: QueryArgFrom<Definitions[EndpointName]>, options: PrefetchOptions): ThunkAction<void, any, any, AnyAction>;
167 /**
168 * 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.
169 *
170 * The thunk action creator accepts three arguments: the name of the endpoint we are updating (such as `'getPost'`), the appropriate query arg values to construct the desired cache key, and an `updateRecipe` 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.
171 *
172 * The thunk executes _synchronously_, and 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).
173 *
174 * 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.
175 *
176 * Note that the first two arguments (`endpointName` and `args`) are used to determine which existing cache entry to update. If no existing cache entry is found, the `updateRecipe` callback will not run.
177 *
178 * @example
179 *
180 * ```ts
181 * const patchCollection = dispatch(
182 * api.util.updateQueryData('getPosts', undefined, (draftPosts) => {
183 * draftPosts.push({ id: 1, name: 'Teddy' })
184 * })
185 * )
186 * ```
187 */
188 updateQueryData: UpdateQueryDataThunk<Definitions, RootState<Definitions, string, ReducerPath>>;
189 /** @deprecated renamed to `updateQueryData` */
190 updateQueryResult: UpdateQueryDataThunk<Definitions, RootState<Definitions, string, ReducerPath>>;
191 /**
192 * A Redux thunk action creator that, when dispatched, acts as an artificial API request to upsert a value into the cache.
193 *
194 * The thunk action creator accepts three arguments: the name of the endpoint we are updating (such as `'getPost'`), the appropriate query arg values to construct the desired cache key, and the data to upsert.
195 *
196 * If no cache entry for that cache key exists, a cache entry will be created and the data added. If a cache entry already exists, this will _overwrite_ the existing cache entry data.
197 *
198 * The thunk executes _asynchronously_, and returns a promise that resolves when the store has been updated.
199 *
200 * If dispatched while an actual request is in progress, both the upsert and request will be handled as soon as they resolve, resulting in a "last result wins" update behavior.
201 *
202 * @example
203 *
204 * ```ts
205 * await dispatch(
206 * api.util.upsertQueryData('getPost', {id: 1}, {id: 1, text: "Hello!"})
207 * )
208 * ```
209 */
210 upsertQueryData: UpsertQueryDataThunk<Definitions, RootState<Definitions, string, ReducerPath>>;
211 /**
212 * 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.
213 *
214 * The thunk accepts three arguments: the name of the endpoint we are updating (such as `'getPost'`), the appropriate query arg values to construct the desired cache key, and a JSON diff/patch array as produced by Immer's `produceWithPatches`.
215 *
216 * 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.
217 *
218 * 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.
219 *
220 * @example
221 * ```ts
222 * const patchCollection = dispatch(
223 * api.util.updateQueryData('getPosts', undefined, (draftPosts) => {
224 * draftPosts.push({ id: 1, name: 'Teddy' })
225 * })
226 * )
227 *
228 * // later
229 * dispatch(
230 * api.util.patchQueryData('getPosts', undefined, patchCollection.inversePatches)
231 * )
232 *
233 * // or
234 * patchCollection.undo()
235 * ```
236 */
237 patchQueryData: PatchQueryDataThunk<Definitions, RootState<Definitions, string, ReducerPath>>;
238 /** @deprecated renamed to `patchQueryData` */
239 patchQueryResult: PatchQueryDataThunk<Definitions, RootState<Definitions, string, ReducerPath>>;
240 /**
241 * 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'.
242 *
243 * @example
244 *
245 * ```ts
246 * dispatch(api.util.resetApiState())
247 * ```
248 */
249 resetApiState: SliceActions['resetApiState'];
250 /**
251 * A Redux action creator that can be used to manually invalidate cache tags for [automated re-fetching](../../usage/automated-refetching.mdx).
252 *
253 * 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.
254 *
255 * 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.
256 *
257 * 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:
258 *
259 * - `[TagType]`
260 * - `[{ type: TagType }]`
261 * - `[{ type: TagType, id: number | string }]`
262 *
263 * @example
264 *
265 * ```ts
266 * dispatch(api.util.invalidateTags(['Post']))
267 * dispatch(api.util.invalidateTags([{ type: 'Post', id: 1 }]))
268 * dispatch(
269 * api.util.invalidateTags([
270 * { type: 'Post', id: 1 },
271 * { type: 'Post', id: 'LIST' },
272 * ])
273 * )
274 * ```
275 */
276 invalidateTags: ActionCreatorWithPayload<Array<TagDescription<TagTypes>>, string>;
277 /**
278 * A function to select all `{ endpointName, originalArgs, queryCacheKey }` combinations that would be invalidated by a specific set of tags.
279 *
280 * Can be used for mutations that want to do optimistic updates instead of invalidating a set of tags, but don't know exactly what they need to update.
281 */
282 selectInvalidatedBy: (state: RootState<Definitions, string, ReducerPath>, tags: ReadonlyArray<TagDescription<TagTypes>>) => Array<{
283 endpointName: string;
284 originalArgs: any;
285 queryCacheKey: string;
286 }>;
287 };
288 /**
289 * Endpoints based on the input endpoints provided to `createApi`, containing `select` and `action matchers`.
290 */
291 endpoints: {
292 [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;
293 };
294 };
295 }
296}
297export interface ApiEndpointQuery<Definition extends QueryDefinition<any, any, any, any, any>, Definitions extends EndpointDefinitions> {
298 name: string;
299 /**
300 * All of these are `undefined` at runtime, purely to be used in TypeScript declarations!
301 */
302 Types: NonNullable<Definition['Types']>;
303}
304export interface ApiEndpointMutation<Definition extends MutationDefinition<any, any, any, any, any>, Definitions extends EndpointDefinitions> {
305 name: string;
306 /**
307 * All of these are `undefined` at runtime, purely to be used in TypeScript declarations!
308 */
309 Types: NonNullable<Definition['Types']>;
310}
311export declare type ListenerActions = {
312 /**
313 * Will cause the RTK Query middleware to trigger any refetchOnReconnect-related behavior
314 * @link https://rtk-query-docs.netlify.app/api/setupListeners
315 */
316 onOnline: typeof onOnline;
317 onOffline: typeof onOffline;
318 /**
319 * Will cause the RTK Query middleware to trigger any refetchOnFocus-related behavior
320 * @link https://rtk-query-docs.netlify.app/api/setupListeners
321 */
322 onFocus: typeof onFocus;
323 onFocusLost: typeof onFocusLost;
324};
325export declare type InternalActions = SliceActions & ListenerActions;
326/**
327 * Creates a module containing the basic redux logic for use with `buildCreateApi`.
328 *
329 * @example
330 * ```ts
331 * const createBaseApi = buildCreateApi(coreModule());
332 * ```
333 */
334export declare const coreModule: () => Module<CoreModule>;