Asynchronous Tasks
Performing asynchronous tasks in Redux involves writing complex hard maintainable code which can result in lot of errors. With Redux Toolkit, we can use ‘createAsyncThunk’ which helps in the process of dispatching actions. It reduces the complexity of code in managing async operations. See how simple our code becomes.
// Redux code without Redux Toolkit
const FETCH_TODO_REQUEST = 'FETCH_TODO_REQUEST';
const FETCH_TODO_SUCCESS = 'FETCH_TODO_SUCCESS';
const FETCH_TODO_FAILURE = 'FETCH_TODO_FAILURE';
function fetchTodoRequest() {
return { type: FETCH_TODO_REQUEST };
}
function fetchTodoSuccess(data) {
return { type: FETCH_TODO_SUCCESS, payload: data };
}
function fetchTodoFailure(error) {
return { type: FETCH_TODO_FAILURE, payload: error };
}
function fetchTodo() {
return dispatch => {
dispatch(fetchTodoRequest());
fetch('https://api.example.com/todos')
.then(response => response.json())
.then(
data => dispatch(fetchTodoSuccess(data)))
.catch(
error => dispatch(fetchTodoFailure(error)));
};
}
// Redux Toolkit code
import { createAsyncThunk } from '@reduxjs/toolkit';
const fetchTodo = createAsyncThunk('todos/fetchTodo', async () => {
const response = await fetch('https://api.example.com/todos');
return response.json();
});
These are the important reasons why the Redux Toolkit was created. You can also check all the other reasons from the documentation, refer to this link: Why Redux Toolkit is How To Use Redux Today
Why was Redux Toolkit created?
Redux Toolkit was created to improve the overall development experience and to simplify the setup of the redux store and state management tasks. Redux Toolkit is also known as RTK in short. In this article, we’ll discuss the problems that developers face while using Redux and how Redux Toolkit comes up with the solution.
Table of Content
- Too much Boilerplate Code
- Accidental state mutation
- Typescript Support
- Asynchronous Tasks
Contact Us