Skip to content

Commit 873a647

Browse files
committed
Improve doc clarity around TypeScript and createAsyncThunk usage
1 parent 6a3de08 commit 873a647

File tree

1 file changed

+15
-0
lines changed

1 file changed

+15
-0
lines changed

docs/usage/usage-with-typescript.md

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -557,6 +557,21 @@ const fetchUserById = createAsyncThunk(
557557
const lastReturnedAction = await store.dispatch(fetchUserById(3))
558558
```
559559

560+
### Handling responses from async thunks
561+
562+
The preferred approach to handling responses from thunks is via the `unwrap` method (see [Unwrapping Result Actions](../api/createAsyncThunk.mdx/#unwrapping-result-actions).
563+
564+
```ts
565+
const handleClick = async (userData) => {
566+
try {
567+
const result = await dispatch(updateUser(userData)).unwrap();
568+
showToast('success', `Updated ${result.name}`)
569+
} catch (error) {
570+
showToast('error', `Update failed: ${error.message}`)
571+
}
572+
}
573+
```
574+
560575
### Typing the `thunkApi` Object
561576

562577
The second argument to the `payloadCreator`, known as `thunkApi`, is an object containing references to the `dispatch`, `getState`, and `extra` arguments from the thunk middleware as well as a utility function called `rejectWithValue`. If you want to use these from within the `payloadCreator`, you will need to define some generic arguments, as the types for these arguments cannot be inferred. Also, as TS cannot mix explicit and inferred generic parameters, from this point on you'll have to define the `Returned` and `ThunkArg` generic parameter as well.

0 commit comments

Comments
 (0)