How do you handle async operations in Redux Toolkit with createAsyncThunk?

Answer

createAsyncThunk is RTK's utility for defining async thunk action creators. It auto-generates lifecycle actions. Define: const fetchUser = createAsyncThunk("users/fetchById", async (userId, { rejectWithValue }) => { try { return await api.getUser(userId); } catch (err) { return rejectWithValue(err.response.data); } });. Handle in slice: extraReducers: (builder) => { builder .addCase(fetchUser.pending, (state) => { state.loading = true; }) .addCase(fetchUser.fulfilled, (state, action) => { state.loading = false; state.user = action.payload; }) .addCase(fetchUser.rejected, (state, action) => { state.loading = false; state.error = action.payload; }); }. Dispatch: dispatch(fetchUser(42)). rejectWithValue: pass error data to the rejected action. thunkAPI: second parameter gives access to dispatch, getState, signal (AbortSignal for cancellation). Cancellation: const promise = dispatch(fetchUser(42)); promise.abort();. Auto-generated action types: users/fetchById/pending, users/fetchById/fulfilled, users/fetchById/rejected.