Skip to content

Commit

Permalink
Merge branch 'master' of https://github.com/reduxjs/redux-toolkit int…
Browse files Browse the repository at this point in the history
…o fix-composeWithDevTools-spy
  • Loading branch information
aryaemami59 committed Jan 20, 2024
2 parents 3a5074c + 3c50985 commit ed1d21e
Show file tree
Hide file tree
Showing 3 changed files with 12 additions and 5 deletions.
2 changes: 1 addition & 1 deletion docs/api/createAsyncThunk.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -527,7 +527,7 @@ If a thunk was cancelled, the result of the promise will be a `rejected` action
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'
import { createAsyncThunk } from '@reduxjs/toolkit'

test('this thunk should always be skipped', async () => {
const thunk = createAsyncThunk(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ const slice = createSlice({
console.log('fulfilled', action)
state.user = action.payload.user
state.token = action.payload.token
state.isAuthenticated = true
})
.addMatcher(postsApi.endpoints.login.matchRejected, (state, action) => {
console.log('rejected', action)
Expand Down
14 changes: 10 additions & 4 deletions packages/toolkit/src/createAsyncThunk.ts
Original file line number Diff line number Diff line change
Expand Up @@ -577,6 +577,7 @@ export const createAsyncThunk = /* @__PURE__ */ (() => {
: nanoid()

const abortController = new AbortController()
let abortHandler: (() => void) | undefined
let abortReason: string | undefined

function abort(reason?: string) {
Expand All @@ -600,14 +601,15 @@ export const createAsyncThunk = /* @__PURE__ */ (() => {
}
}

const abortedPromise = new Promise<never>((_, reject) =>
abortController.signal.addEventListener('abort', () =>
const abortedPromise = new Promise<never>((_, reject) => {
abortHandler = () => {
reject({
name: 'AbortError',
message: abortReason || 'Aborted',
})
)
)
}
abortController.signal.addEventListener('abort', abortHandler)
})
dispatch(
pending(
requestId,
Expand Down Expand Up @@ -653,6 +655,10 @@ export const createAsyncThunk = /* @__PURE__ */ (() => {
err instanceof RejectWithValue
? rejected(null, requestId, arg, err.payload, err.meta)
: rejected(err as any, requestId, arg)
} finally {
if (abortHandler) {
abortController.signal.removeEventListener('abort', abortHandler)
}
}
// We dispatch the result action _after_ the catch, to avoid having any errors
// here get swallowed by the try/catch block,
Expand Down

0 comments on commit ed1d21e

Please sign in to comment.