Skip to content

Commit 24179aa

Browse files
authored
Merge pull request #1631 from Shrugsy/docs/update-mutation-documentation
2 parents 9e36af6 + 82a6345 commit 24179aa

File tree

3 files changed

+66
-5
lines changed

3 files changed

+66
-5
lines changed

docs/rtk-query/api/created-api/hooks.mdx

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -315,6 +315,8 @@ type UseMutation = (
315315
type UseMutationStateOptions = {
316316
// A method to determine the contents of `UseMutationResult`
317317
selectFromResult?: (result: UseMutationStateDefaultResult) => any
318+
// A string used to enable shared results across hook instances which have the same key
319+
fixedCacheKey?: string
318320
}
319321

320322
type UseMutationTrigger<T> = (arg: any) => Promise<
@@ -323,12 +325,12 @@ type UseMutationTrigger<T> = (arg: any) => Promise<
323325
requestId: string // A string generated by RTK Query
324326
abort: () => void // A method to cancel the mutation promise
325327
unwrap: () => Promise<T> // A method to unwrap the mutation call and provide the raw response/error
326-
unsubscribe: () => void // A method to manually unsubscribe from the mutation call
328+
reset: () => void // A method to manually unsubscribe from the mutation call and reset the result to the uninitialized state
327329
}
328330

329331
type UseMutationResult<T> = {
330332
// Base query state
331-
originalArgs?: unknown // Arguments passed to the latest mutation call
333+
originalArgs?: unknown // Arguments passed to the latest mutation call. Not available if using the `fixedCacheKey` option
332334
data?: T // Returned result if present
333335
error?: unknown // Error result if present
334336
endpointName?: string // The name of the given endpoint for the mutation
@@ -340,6 +342,8 @@ type UseMutationResult<T> = {
340342
isSuccess: boolean // Mutation has data from a successful call
341343
isError: boolean // Mutation is currently in an "error" state
342344
startedTimeStamp?: number // Timestamp for when the latest mutation was initiated
345+
346+
reset: () => void // A method to manually unsubscribe from the mutation call and reset the result to the uninitialized state
343347
}
344348
```
345349
@@ -357,7 +361,9 @@ selectFromResult: () => ({})
357361
358362
- **Parameters**
359363
360-
- `options`: A set of options that control the subscription behavior of the hook
364+
- `options`: A set of options that control the subscription behavior of the hook:
365+
- `selectFromResult`: A callback that can be used to customize the mutation result returned as the second item in the tuple
366+
- `fixedCacheKey`: An optional string used to enable shared results across hook instances
361367
362368
- **Returns**: A tuple containing:
363369
- `trigger`: A function that triggers an update to the data based on the provided argument. The trigger function returns a promise with the properties shown above that may be used to handle the behavior of the promise

docs/rtk-query/usage/error-handling.mdx

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -94,7 +94,7 @@ import { toast } from 'your-cool-library'
9494
export const rtkQueryErrorLogger: Middleware = (api: MiddlewareAPI) => (
9595
next
9696
) => (action) => {
97-
// RTK Query uses `createAsyncThunk` from redux-toolkit under the hood, so we're able to utilize these use matchers!
97+
// RTK Query uses `createAsyncThunk` from redux-toolkit under the hood, so we're able to utilize these matchers!
9898
if (isRejectedWithValue(action)) {
9999
console.warn('We got a rejected action!')
100100
toast.warn({ title: 'Async error!', message: action.error.data.message })

docs/rtk-query/usage/mutations.mdx

Lines changed: 56 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -109,16 +109,71 @@ Below are some of the most frequently used properties on the "mutation result" o
109109
- `isLoading` - When true, indicates that the mutation has been fired and is awaiting a response.
110110
- `isSuccess` - When true, indicates that the last mutation fired has data from a successful request.
111111
- `isError` - When true, indicates that the last mutation fired resulted in an error state.
112+
- `reset` - A method to reset the hook back to it's original state and remove the current result from the cache
112113

113114
:::note
114115

115116
With RTK Query, a mutation does not contain a semantic distinction between 'loading' and 'fetching' in the way that a [query does](./queries.mdx#frequently-used-query-hook-return-values). For a mutation, subsequent calls are not assumed to be necessarily related, so a mutation is either 'loading' or 'not loading', with no concept of 're-fetching'.
116117

117118
:::
118119

120+
### Shared Mutation Results
121+
122+
By default, separate instances of a `useMutation` hook are not inherently related to each other.
123+
Triggering one instance will not affect the result for a separate instance. This applies regardless
124+
of whether the hooks are called within the same component, or different components.
125+
126+
```tsx no-transpile
127+
export const ComponentOne = () => {
128+
// Triggering `updatePostOne` will affect the result in this component,
129+
// but not the result in `ComponentTwo`, and vice-versa
130+
const [updatePost, result] = useUpdatePostMutation()
131+
132+
return <div>...</div>
133+
}
134+
135+
export const ComponentTwo = () => {
136+
const [updatePost, result] = useUpdatePostMutation()
137+
138+
return <div>...</div>
139+
}
140+
```
141+
142+
RTK Query provides an option to share results across mutation hook instances using the
143+
`fixedCacheKey` option.
144+
Any `useMutation` hooks with the same `fixedCacheKey` string will share results between each other
145+
when any of the trigger functions are called. This should be a unique string shared between each
146+
mutation hook instance you wish to share results.
147+
148+
```tsx no-transpile
149+
export const ComponentOne = () => {
150+
// Triggering `updatePostOne` will affect the result in both this component,
151+
// but as well as the result in `ComponentTwo`, and vice-versa
152+
const [updatePost, result] = useUpdatePostMutation({
153+
fixedCacheKey: 'shared-update-post',
154+
})
155+
156+
return <div>...</div>
157+
}
158+
159+
export const ComponentTwo = () => {
160+
const [updatePost, result] = useUpdatePostMutation({
161+
fixedCacheKey: 'shared-update-post',
162+
})
163+
164+
return <div>...</div>
165+
}
166+
```
167+
168+
:::note
169+
170+
When using `fixedCacheKey`, the `originalArgs` property is not able to be shared and will always be `undefined`.
171+
172+
:::
173+
119174
### Standard Mutation Example
120175

121-
This is a modified version of the complete example you can see at the bottom of the page to highlight the `updatePost` mutation. In this scenario, a post is fetched with `useQuery`, and then a `EditablePostName` component is rendered that allows us to edit the name of the post.
176+
This is a modified version of the complete example you can see at the bottom of the page to highlight the `updatePost` mutation. In this scenario, a post is fetched with `useQuery`, and then an `EditablePostName` component is rendered that allows us to edit the name of the post.
122177

123178
```tsx title="src/features/posts/PostDetail.tsx"
124179
export const PostDetail = () => {

0 commit comments

Comments
 (0)