Date:

Use Redux Toolkit’s createAsyncThunk for Async Data Fetching

Create AsyncThunk in Redux Toolkit

createAsyncThunk() is a function in the Redux Toolkit that is used to handle async operations such as API calls. This function automatically handles three main phases: pending, fulfilled, and rejected.

Create postSlice

import { createAsyncThunk, createSlice } from '@reduxjs/toolkit';
import axios from 'axios';

interface Post {
  id: number;
  title: string;
  body: string;
}

interface PostState {
  posts: Post[];
  loading: boolean;
  error: string | null;
}

const initialState: PostState = {
  posts: [],
  loading: false,
  error: null,
};

export const fetchPosts = createAsyncThunk(
  'posts/fetchPosts',
  async () => {
    const response = await axios.get('https://jsonplaceholder.typicode.com/posts');
    return response.data;
  }
);

const postSlice = createSlice({
  name: 'posts',
  initialState,
  reducers: {},
  extraReducers: (builder) => {
    builder
     .addCase(fetchPosts.pending, (state) => {
        state.loading = true;
      })
     .addCase(fetchPosts.fulfilled, (state, action) => {
        state.loading = false;
        state.posts = action.payload;
      })
     .addCase(fetchPosts.rejected, (state, action) => {
        state.loading = false;
        state.error = action.error.message || 'Failed to fetch posts';
      });
  },
});

export default postSlice.reducer;

Result

If you get this error, update store.ts and add middleware.

Error

Add Middleware

import { configureStore } from '@reduxjs/toolkit';
import { counterReducer } from './slice/counterSlice';
import { postsReducer } from './slice/postSlice';
import { persistReducer, persistStore } from 'redux-persist';
import storage from 'redux-persist/lib/storage';

const persistConfig = {
  key: 'root',
  storage,
};

const persistedCounterReducer = persistReducer(persistConfig, counterReducer);

export const store = configureStore({
  reducer: {
    counter: persistedCounterReducer,
    posts: postsReducer,
  },
  middleware: (getDefaultMiddleware) =>
    getDefaultMiddleware({
      serializableCheck: {
        ignoredActions: ['persist/PERSIST'],
      },
    }),
});

export const persistor = persistStore(store);

type RootState = ReturnType;
type AppDispatch = typeof store.dispatch;

Conclusion

By using createAsyncThunk() in Redux Toolkit, managing asynchronous operations like API calls becomes easier and more organized. This approach simplifies data fetching while ensuring a clean and scalable Redux state management structure.

I hope this guide helps you better understand Redux Toolkit, especially its async handling capabilities. If you have any questions or feedback, feel free to leave a comment!

GitHub Repo: https://github.com/rfkyalf/redux-toolkit-learn

Also, if you’re interested, feel free to visit my Portfolio Website www.rifkyalfarez.my.id to explore more of my projects. Thank you for reading.

FAQs

Q: What is createAsyncThunk in Redux Toolkit?

A: createAsyncThunk() is a function in the Redux Toolkit that is used to handle async operations such as API calls. This function automatically handles three main phases: pending, fulfilled, and rejected.

Q: What is the purpose of the extraReducers in createSlice?

A: The extraReducers in createSlice are used to add additional reducers to the slice. In this case, it is used to add the reducers for the async operation.

Q: What is persistStore in Redux Toolkit?

A: persistStore is a function in Redux Toolkit that persists the state of the store to local storage. This allows the state to be recovered when the application is reloaded.

Q: What is the purpose of the middleware in Redux Toolkit?

A: The middleware in Redux Toolkit is used to add additional functionality to the store. In this case, it is used to add the serializableCheck middleware, which allows the store to be persisted.

Latest stories

Read More

LEAVE A REPLY

Please enter your comment!
Please enter your name here