Skip to content

Commit ae2a3c6

Browse files
authored
Merge pull request #2129 from sgnilreutr/master
2 parents 5492281 + a9adf6d commit ae2a3c6

File tree

1 file changed

+26
-16
lines changed

1 file changed

+26
-16
lines changed

docs/api/createAsyncThunk.mdx

Lines changed: 26 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -25,23 +25,33 @@ Redux Toolkit's [**RTK Query data fetching API**](../rtk-query/overview.md) is a
2525

2626
Sample usage:
2727

28-
```js {5-11,22-25,30}
28+
```ts no-transpile {5-11,22-25,30}
2929
import { createAsyncThunk, createSlice } from '@reduxjs/toolkit'
3030
import { userAPI } from './userAPI'
3131

3232
// First, create the thunk
3333
const fetchUserById = createAsyncThunk(
3434
'users/fetchByIdStatus',
35-
async (userId, thunkAPI) => {
35+
async (userId: number, thunkAPI) => {
3636
const response = await userAPI.fetchById(userId)
3737
return response.data
3838
}
3939
)
4040

41+
interface UsersState {
42+
entities: []
43+
loading: 'idle' | 'pending' | 'succeeded' | 'failed'
44+
}
45+
46+
const initialState = {
47+
entities: [],
48+
loading: 'idle',
49+
} as UsersState
50+
4151
// Then, handle actions in your reducers:
4252
const usersSlice = createSlice({
4353
name: 'users',
44-
initialState: { entities: [], loading: 'idle' },
54+
initialState,
4555
reducers: {
4656
// standard reducer logic, with auto-generated action types per reducer
4757
},
@@ -202,7 +212,7 @@ type RejectedWithValue = <ThunkArg, RejectedValue>(
202212
203213
To handle these actions in your reducers, reference the action creators in `createReducer` or `createSlice` using either the object key notation or the "builder callback" notation. (Note that if you use TypeScript, you [should use the "builder callback" notation to ensure the types are inferred correctly](../usage/usage-with-typescript.md#type-safety-with-extrareducers)):
204214
205-
```js {2,6,14,23}
215+
```ts no-transpile {2,6,14,23}
206216
const reducer1 = createReducer(initialState, {
207217
[fetchUserById.fulfilled]: (state, action) => {},
208218
})
@@ -236,7 +246,7 @@ const reducer4 = createSlice({
236246

237247
Thunks may return a value when dispatched. A common use case is to return a promise from the thunk, dispatch the thunk from a component, and then wait for the promise to resolve before doing additional work:
238248

239-
```js
249+
```ts no-transpile
240250
const onClick = () => {
241251
dispatch(fetchUserById(userId)).then(() => {
242252
// do additional work
@@ -336,7 +346,7 @@ If you need to customize the contents of the `rejected` action, you should catch
336346

337347
The `rejectWithValue` approach should also be used if your API response "succeeds", but contains some kind of additional error details that the reducer should know about. This is particularly common when expecting field-level validation errors from an API.
338348

339-
```js
349+
```ts no-transpile
340350
const updateUser = createAsyncThunk(
341351
'users/update',
342352
async (userData, { rejectWithValue }) => {
@@ -359,10 +369,10 @@ const updateUser = createAsyncThunk(
359369

360370
If you need to cancel a thunk before the payload creator is called, you may provide a `condition` callback as an option after the payload creator. The callback will receive the thunk argument and an object with `{getState, extra}` as parameters, and use those to decide whether to continue or not. If the execution should be canceled, the `condition` callback should return a literal `false` value or a promise that should resolve to `false`. If a promise is returned, the thunk waits for it to get fulfilled before dispatching the `pending` action, otherwise it proceeds with dispatching synchronously.
361371

362-
```js
372+
```ts no-transpile
363373
const fetchUserById = createAsyncThunk(
364374
'users/fetchByIdStatus',
365-
async (userId, thunkAPI) => {
375+
async (userId: number, thunkAPI) => {
366376
const response = await userAPI.fetchById(userId)
367377
return response.data
368378
},
@@ -387,7 +397,7 @@ If you want to cancel your running thunk before it has finished, you can use the
387397

388398
A real-life example of that would look like this:
389399

390-
```ts
400+
```ts no-transpile
391401
// file: store.ts noEmit
392402
import { configureStore, Reducer } from '@reduxjs/toolkit'
393403
import { useDispatch } from 'react-redux'
@@ -429,7 +439,7 @@ Additionally, your `payloadCreator` can use the `AbortSignal` it is passed via `
429439

430440
The `fetch` api of modern browsers already comes with support for an `AbortSignal`:
431441

432-
```ts
442+
```ts no-transpile
433443
import { createAsyncThunk } from '@reduxjs/toolkit'
434444

435445
const fetchUserById = createAsyncThunk(
@@ -449,7 +459,7 @@ const fetchUserById = createAsyncThunk(
449459

450460
You can use the `signal.aborted` property to regularly check if the thunk has been aborted and in that case stop costly long-running work:
451461

452-
```ts
462+
```ts no-transpile
453463
import { createAsyncThunk } from '@reduxjs/toolkit'
454464

455465
const readStream = createAsyncThunk(
@@ -478,13 +488,13 @@ const readStream = createAsyncThunk(
478488
You can also call `signal.addEventListener('abort', callback)` to have logic inside the thunk be notified when `promise.abort()` was called.
479489
This can for example be used in conjunction with an axios `CancelToken`:
480490

481-
```ts
491+
```ts no-transpile
482492
import { createAsyncThunk } from '@reduxjs/toolkit'
483493
import axios from 'axios'
484494

485495
const fetchUserById = createAsyncThunk(
486496
'users/fetchById',
487-
async (userId, { signal }) => {
497+
async (userId: string, { signal }) => {
488498
const source = axios.CancelToken.source()
489499
signal.addEventListener('abort', () => {
490500
source.cancel()
@@ -501,13 +511,13 @@ const fetchUserById = createAsyncThunk(
501511

502512
- Requesting a user by ID, with loading state, and only one request at a time:
503513

504-
```js
514+
```ts no-transpile
505515
import { createAsyncThunk, createSlice } from '@reduxjs/toolkit'
506516
import { userAPI } from './userAPI'
507517

508518
const fetchUserById = createAsyncThunk(
509519
'users/fetchByIdStatus',
510-
async (userId, { getState, requestId }) => {
520+
async (userId: string, { getState, requestId }) => {
511521
const { currentRequestId, loading } = getState().users
512522
if (loading !== 'pending' || requestId !== currentRequestId) {
513523
return
@@ -580,7 +590,7 @@ const UsersComponent = () => {
580590

581591
_Note: this is a contrived example assuming our userAPI only ever throws validation-specific errors_
582592

583-
```ts
593+
```ts no-transpile
584594
// file: store.ts noEmit
585595
import { configureStore, Reducer } from '@reduxjs/toolkit'
586596
import { useDispatch } from 'react-redux'

0 commit comments

Comments
 (0)