Redux implements async fetching with the help of Thunk. Thunk is special function which re fetch data and update the state automatically, it is like a magical wheel behind your app.

Create thunk with slice

Redux-toolkit included special function for creating the fetching logic and later implement in the slice.

//userSlice import {    createAsyncThunk,    createSlice,    PayloadAction,  } from '@reduxjs/toolkit';      interface User {    id: number;    email: string;    name: string;  }  // declaring the types for our state  export type UserState = {    data: User[];    pending: boolean;    error: boolean;  };    const initialState: UserState = {    data:[],    pending: false,    error: false  };    export const getUser = createAsyncThunk('user/getUser', async () => {    console.log('Thunk invoked');    const res = await fetch("http://localhost:3000/api/users?limit=100");    const data =await res.json();         return data.users;   });       export const userSlice = createSlice({    name: 'user',    initialState,        extraReducers: builder => {      builder        .addCase(getUser.fulfilled, (state, { payload }) => {        state.data=payload        })        .addCase(getUser.pending, (state, { payload }) => {          state.pending=true          })        }  });   export const selectUser = (state: RootState) =>state.user.data   export default userSlice.reducer;          

As you may note, it is an external function, deserve a special special reducer for it. In extra reducer section implement the Thunk.

How to call

useDispatch hook can be used to make call to the getUser async call.

    import { useAppDispatch, useAppSelector } from "../hooks";  import { selectUser, getUser } from '../fetures/users/userSlice'; ....   const data = useAppSelector(selectUser);    const dispatch = useAppDispatch();    dispatch(getUser())

Open the developer tool and watch it refetch data for you.


This free site is ad-supported. Learn more