Global state management using ReduxToolKit(rtk)

Author : JaNakh Pon , January 07, 2022

Tags

Introduction

The Redux Toolkit is developed by the redux/react-redux team and it provides a more enchanced way to write redux code.

Getting Started with Redux Toolkit

RTK Installation

Firstly, let's install the required dependencies 😉:

  > npm install @reduxjs/toolkit || yarn add @reduxjs/toolkit

createStore

We will use configureStore from RTK to create redux store and it will not only create the store but also combine the reducers for us.

Moreover, RTK has redux-thunk by default, so we dont need to configure applyMiddleware() with thunk for async functions.

What's Included

redux/slices/index.js
import { configureStore } from "@reduxjs/toolkit";
import task from "./task";

export const store = configureStore({
  reducer: {
    task,
  },
});

createSlice

Create a Redux State Slice

createSlice

createAsyncThunk

In our previous article with Redux, we had seperate folders,files for reducers and actions but in RTK, we will only need slices.

A slice contains the initialState data, reducers/functions() and actions.

redux/slices/task/index.js
import axios from "axios";
import { createSlice, createAsyncThunk } from "@reduxjs/toolkit";
import { URL } from "../../../utils/task.common";

export const getTasksCount = createAsyncThunk(
  "task/getTasksCount",
  async () => {
    let tkCount = await axios({
      method: "get",
      url: `${URL}/count`,
    });
    return tkCount.data.count;
  }
);

// ....

const taskSlice = createSlice({
  name: "task",
  initialState: {
    taskList: [],
    searchList: [],
    task: {},
    count: 0,
    searchCount: 0,
    error: null,
    msg: null,
    loading: false,
  },
  reducers: {},
  extraReducers: {
    [getTasksCount.pending.toString()]: (state, action) => {
      console.log("Feting Count => getTasksCount");
    },
    [getTasksCount.fulfilled.toString()]: (state, action) => {
      state.count = action.payload;
    },
    [listTasks.fulfilled.toString()]: (state, action) => {
      state.taskList = action.payload;
    },
    [createTask.fulfilled.toString()]: (state, action) => {
      state.taskList = [...state.taskList, action.payload];
    },
    [removeTask.fulfilled.toString()]: (state, action) => {
      state.taskList = state.taskList.filter((tk) => tk.id !== action.payload);
    },
    [updateTask.fulfilled.toString()]: (state, action) => {
      state.taskList = state.taskList.map((x) =>
        x.id === action.payload.id
          ? { ...x, completed: action.payload.completed }
          : x
      );
    },
    [searchTasks.fulfilled.toString()]: (state, action) => {
      console.log("action.payload.count", action.payload.count)
      state.searchCount = action.payload.count
      state.searchList = action.payload.data
    },
  },
});

export default taskSlice.reducer;

And the rest is the same as redux implementation in our previous article.

RTK also has a powerful data fetching and caching tool known as RTK Query.

Source Code.