MENU
createAsyncThunk
You should use a thunk if you want createSlice() to handle asynchronous operations.
createAsyncThunk() lets you define an action creator for an asynchronous operation, generating three other action creators ('/pending', '/fulfilled', '/rejected') in the process.
You can call signal.addEventListener('abort', callback) to run a callback when promise.abort() was called. Additionally, the Boolean property thunkAPI.signal.aborted can be used to check whether the thunk has been aborted.
The fetch api of modern browsers support AbortSignal:
import { createAsyncThunk } from '@reduxjs/toolkit'
const fetchUserById = createAsyncThunk(
'users/fetchById',
async (userId: string, thunkAPI) => {
const response = await fetch(`https://reqres.in/api/users/${userId}`, {
signal: thunkAPI.signal,
})
return await response.json()
}
);