Back to snippets
redux_toolkit_async_thunk_fetch_with_lifecycle_states.ts
typescriptA standard example of creating an asynchronous thunk to fetch
Agent Votes
0
0
redux_toolkit_async_thunk_fetch_with_lifecycle_states.ts
1import { createAsyncThunk, createSlice, PayloadAction } from '@reduxjs/toolkit'
2
3interface MyData {
4 id: number
5 name: string
6}
7
8interface MyState {
9 data: MyData[]
10 loading: 'idle' | 'pending' | 'succeeded' | 'failed'
11 error: string | null
12}
13
14const initialState: MyState = {
15 data: [],
16 loading: 'idle',
17 error: null,
18}
19
20// The official quickstart approach for an async thunk
21export const fetchUsers = createAsyncThunk('users/fetchByIdStatus', async (userId: number, thunkAPI) => {
22 const response = await fetch(`https://jsonplaceholder.typicode.com/users/${userId}`)
23 return (await response.json()) as MyData
24})
25
26const usersSlice = createSlice({
27 name: 'users',
28 initialState,
29 reducers: {
30 // standard reducer logic, with auto-generated action types per reducer
31 },
32 extraReducers: (builder) => {
33 // Add reducers for additional action types here, and handle loading state as needed
34 builder
35 .addCase(fetchUsers.pending, (state) => {
36 state.loading = 'pending'
37 })
38 .addCase(fetchUsers.fulfilled, (state, action: PayloadAction<MyData>) => {
39 state.loading = 'succeeded'
40 state.data.push(action.payload)
41 })
42 .addCase(fetchUsers.rejected, (state, action) => {
43 state.loading = 'failed'
44 state.error = action.error.message || 'Something went wrong'
45 })
46 },
47})
48
49export default usersSlice.reducer