Skip to content

Commit

Permalink
Merge pull request #2383 from josh-degraw/docs
Browse files Browse the repository at this point in the history
  • Loading branch information
markerikson authored Jun 22, 2022
2 parents 9c4e157 + 3830399 commit a05ed0c
Showing 1 changed file with 30 additions and 0 deletions.
30 changes: 30 additions & 0 deletions docs/api/createAsyncThunk.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -507,6 +507,36 @@ const fetchUserById = createAsyncThunk(
)
```

### Checking if a Promise Rejection was from an Error or Cancellation

To investigate behavior around thunk cancellation, you can inspect various properties on the `meta` object of the dispatched action.
If a thunk was cancelled, the result of the promise will be a `rejected` action (regardless of whether that action was actually dispatched to the store).

- If it was cancelled before execution, `meta.condition` will be true.
- If it was aborted while running, `meta.aborted` will be true.
- If neither of those is true, the thunk was not cancelled, it was simply rejected, either by a Promise rejection or `rejectWithValue`.
- If the thunk was not rejected, both `meta.aborted` and `meta.condition` will be `undefined`.

So if you wanted to test that a thunk was cancelled before executing, you can do the following:

```ts no-transpile
import { createAsyncThunk, isRejected } from '@reduxjs/toolkit'

test('this thunk should always be skipped', async () => {
const thunk = createAsyncThunk(
'users/fetchById',
async () => throw new Error('This promise should never be entered'),
{
condition: () => false,
}
)
const result = await thunk()(dispatch, getState, null)

expect(result.meta.condition).toBe(true)
expect(result.meta.aborted).toBe(false)
})
```

## Examples

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

0 comments on commit a05ed0c

Please sign in to comment.