Async Operation in RTK

Async Operation in RTK

RTK app that uses thunk middleware to fetch data from api and store them in the state.

const { createSlice, createAsyncThunk } = require("@reduxjs/toolkit");
const fetch = require("node-fetch");

// initial state
const initialState = {
  loading: false,
  posts: [],
  error: "",
};

// creating async thunk
const fetchPosts = createAsyncThunk("post/fetchPosts", async () => {
  const res = await fetch(
    "https://jsonplaceholder.typicode.com/todos?_limit=5" // fetch data from api
  );

  const posts = await res.json(); // store data

  return posts;
});

// creating slice
const postSlice = createSlice({
  // Name of the slice
  name: "post",

  // Initial state for the slice
  initialState: initialState,

  // Extra reducers are used to handle actions dispatched by the `fetchPosts` thunk
  extraReducers: (builder) => {
    // When the fetchPosts action is pending, set the loading state to true and clear any previous error
    builder.addCase(fetchPosts.pending, (state, action) => {
      state.loading = true;
      state.error = "";
    });

    // When the fetchPosts action is fulfilled (successfully completed), update the state with the fetched posts
    builder.addCase(fetchPosts.fulfilled, (state, action) => {
      state.loading = false;
      state.error = "";
      state.posts = action.payload;
    });

    // When the fetchPosts action is rejected (failed), update the state with the error and clear the posts array
    builder.addCase(fetchPosts.rejected, (state, action) => {
      state.loading = false;
      state.error = action.error.message;
      state.posts = [];
    });
  },
});

// Exporting the reducer function generated by createSlice
module.exports = postSlice.reducer;

// Exporting the thunk function
module.exports.fetchPosts = fetchPosts;

We don't have to use redux-thunk seperately as RTK manages it automatically.

Last updated

Was this helpful?