Skip to content

Commit 2db682a

Browse files
committed
Add QueryLifecycleMutationExtraOptions
1 parent 5b5a914 commit 2db682a

File tree

1 file changed

+60
-0
lines changed

1 file changed

+60
-0
lines changed

packages/toolkit/src/query/core/buildMiddleware/queryLifecycle.ts

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -116,6 +116,66 @@ export type QueryLifecycleQueryExtraOptions<
116116
): Promise<void> | void
117117
}
118118

119+
export type QueryLifecycleMutationExtraOptions<
120+
ResultType,
121+
QueryArg,
122+
BaseQuery extends BaseQueryFn,
123+
ReducerPath extends string = string,
124+
> = {
125+
/**
126+
* A function that is called when the individual mutation is started. The function is called with a lifecycle api object containing properties such as `queryFulfilled`, allowing code to be run when a query is started, when it succeeds, and when it fails (i.e. throughout the lifecycle of an individual query/mutation call).
127+
*
128+
* Can be used for `optimistic updates`.
129+
*
130+
* @example
131+
*
132+
* ```ts
133+
* import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query'
134+
* export interface Post {
135+
* id: number
136+
* name: string
137+
* }
138+
*
139+
* const api = createApi({
140+
* baseQuery: fetchBaseQuery({
141+
* baseUrl: '/',
142+
* }),
143+
* tagTypes: ['Post'],
144+
* endpoints: (build) => ({
145+
* getPost: build.query<Post, number>({
146+
* query: (id) => `post/${id}`,
147+
* providesTags: ['Post'],
148+
* }),
149+
* updatePost: build.mutation<void, Pick<Post, 'id'> & Partial<Post>>({
150+
* query: ({ id, ...patch }) => ({
151+
* url: `post/${id}`,
152+
* method: 'PATCH',
153+
* body: patch,
154+
* }),
155+
* invalidatesTags: ['Post'],
156+
* async onQueryStarted({ id, ...patch }, { dispatch, queryFulfilled }) {
157+
* const patchResult = dispatch(
158+
* api.util.updateQueryData('getPost', id, (draft) => {
159+
* Object.assign(draft, patch)
160+
* })
161+
* )
162+
* try {
163+
* await queryFulfilled
164+
* } catch {
165+
* patchResult.undo()
166+
* }
167+
* },
168+
* }),
169+
* }),
170+
* })
171+
* ```
172+
*/
173+
onQueryStarted?(
174+
arg: QueryArg,
175+
api: MutationLifecycleApi<QueryArg, BaseQuery, ResultType, ReducerPath>,
176+
): Promise<void> | void
177+
}
178+
119179
export interface QueryLifecycleApi<
120180
QueryArg,
121181
BaseQuery extends BaseQueryFn,

0 commit comments

Comments
 (0)