ReduxJS/Toolkit: createAsyncThunk
Let's do some API calls shall we
createAsyncThunk generates promise lifecycle action types, which you
handle in the extraReducers of your slice.
import { createAsyncThunk } from "@reduxjs/toolkit";
export const fetchStuff = createAsyncThunk(
'resource/action',
async (params, thunkApi) => {
try {
const response = await fetch(`/api/resource/${params.id}`);
return await response.json();
} catch {
// Also possible to return a rejected Promise
return thunkApi.rejectWithValue("Well, that failed");
}
}
);
This dispatches the following actions (from the first “Type” argument):
resource/action/pending: display a spinner or something?resource/action/rejected: display an error message?resource/action/fulfilled: while the previous two could be considered optional, you definitely want to handle this one!

