Horje
Why Do We Need Middleware for Async Flow in Redux?

In Redux, actions are dispatched synchronously, and the state is updated immediately by the reducers. However, real-world applications often involve asynchronous operations like API calls or time-consuming tasks. Without middleware, handling such operations in Redux can lead to complex nested callbacks or promises, making the code difficult to manage. Middleware provides a way to intercept and modify actions before they reach the reducers, enabling developers to handle asynchronous operations elegantly.

Prerequisites:

Approaches

Redux Thunk: A middleware that allows you to write action creators that return a function instead of an action object.

Redux Saga: A middleware library which is used to allow a Redux store to interact asynchronously with resources outside of itself.

Redux Observable: A middleware that allows you to handle asynchronous operations using RxJS Observables.

Steps to Handle Asynchronous Operations using Redux Thunk

Step 1: Install required modules

First, you need to install the required modules for your Redux application with Redux Thunk:

npm install redux react-redux redux-thunk

Project Structure:

Screenshot-2024-06-18-155505[1]

Step 2: Check the Updated dependencies in package.json file:

After installing the required modules, you need to update the package.json file with the corresponding dependencies:

"dependencies": {
"axios": "^1.7.2",
"axioss": "^0.0.1-security",
"react": "^18.3.1",
"react-dom": "^18.3.1",
"react-redux": "^9.1.2",
"react-scripts": "5.0.1",
"redux": "^5.0.1",
"redux-thunk": "^3.1.0",
"web-vitals": "^2.1.4"
}

Step 3: Create a Redux store with the Redux Thunk middleware

JavaScript
import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import rootReducer from './reducers';

const store = createStore(rootReducer, applyMiddleware(thunk));

Step 4: Create an asynchronous action creator using Redux Thunk.

JavaScript
import axios from 'axios';

export const fetchData = () => async (dispatch) => {
  try {
    const response = await axios.get('https://jsonplaceholder.typicode.com/posts'); // Example endpoint
    dispatch({ type: 'FETCH_DATA_SUCCESS', payload: response.data });
  } catch (error) {
    dispatch({ type: 'FETCH_DATA_FAILURE', payload: error.message });
  }
};

Step 5: Dispatch the asynchronous action from your component

JavaScript
import React, { useEffect } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { fetchData } from '../actions';

const MyComponent = () => {
  const dispatch = useDispatch();
  const { items, loading, error } = useSelector(state => state.data); 

  useEffect(() => {
    dispatch(fetchData()); 
  }, [dispatch]);

  if (loading) {
    return <p>Loading...</p>;
  }

  if (error) {
    return <p>Error: {error}</p>;
  }

  return (
    <div>
      <h1>List of Items</h1>
      <p>Items in state: {JSON.stringify(items)}</p> 
      <ul>
        {items.map(item => (
          <li key={item.id}>
            <h3>{item.title}</h3> 
            <p>{item.body}</p>
          </li>
        ))}
      </ul>
    </div>
  );
};

export default MyComponent;

Output:

gfg-article

This is sample data fetched from ‘https://jsonplaceholder.typicode.com/posts’




Reffered: https://www.geeksforgeeks.org


ReactJS

Related
How to Use Redux Toolkit in React For Making API Calls? How to Use Redux Toolkit in React For Making API Calls?
How to Create Memoized Selectors Using Reselect Library? How to Create Memoized Selectors Using Reselect Library?
How to Add Analytics in Next.js with Plausible How to Add Analytics in Next.js with Plausible
How To Get And Process A Stream Response With Axios in NextJS ? How To Get And Process A Stream Response With Axios in NextJS ?
How To Create A Custom Image Loader In NextJS? How To Create A Custom Image Loader In NextJS?

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
17