What is the use of middleware Redux Saga ?
Last Updated :
26 Jul, 2024
What is Redux Saga?
Redux Saga is a middleware library for Redux that provides an elegant way to handle side effects in your React applications. Side effects can include asynchronous actions like making API calls, managing WebSocket connections, and more.
Before we dive into the implementation details, let's gain a basic understanding of Redux Saga.
Redux Saga is built on the concept of generators, a feature introduced in ES6. Generators are special functions that can be paused and resumed, making them perfect for handling asynchronous operations in a non-blocking manner. Redux Saga uses these generators to manage side effects in a declarative and testable way.
Redux workflow with a middleware:
Redux WorkflowRedux-Saga is a library that aims to make application side effects (i.e., asynchronous things like data fetching and impure things like accessing the browser cache) easier to manage, more efficient to execute, easy to test, and better at handling failures.
Setting Up Redux Saga
Step 1: Create a React Application
npx create-react-app saga-app
Step 2: Install Required Packages
cd saga-app
npm install @reduxjs/toolkit react-redux redux-saga
Project Structure:
Now create a index.js file in a directory actions inside the src directory.
Project DirectoryStep 3: Implementing Redux Saga
The saga-app is a React-based web application showcasing Redux Saga, a middleware for handling asynchronous tasks. It fetches data from JSONPlaceholderAPI, a mock RESTful API for testing, and displays it on the web page. Users can delete the displayed data. JSONPlaceholderAPI provides simulated data, making it ideal for testing and development. The app demonstrates how to manage asynchronous actions effectively with Redux Saga in a React application.
Actions:
Create action creators in the actions/index.js file. These actions will be used to trigger sagas.
JavaScript
// actions/index.js
export const fetchDataRequest = () => ({
type: "FETCH_DATA_REQUEST",
});
export const fetchDataSuccess = (data) => ({
type: "FETCH_DATA_SUCCESS",
payload: data,
});
export const fetchDataFailure = (error) => ({
type: "FETCH_DATA_FAILURE",
payload: error,
});
export const deleteDataRequest = () => ({
type: "DELETE_DATA_REQUEST",
});
Reducers:
Create reducers in the reducers/index.js file to manage the state based on the actions.
JavaScript
// reducers/index.js
const initialState = {
data: null,
error: null,
};
const dataReducer = (state = initialState, action) => {
switch (action.type) {
case "FETCH_DATA_SUCCESS":
return {
...state,
data: action.payload,
error: null,
};
case "FETCH_DATA_FAILURE":
return {
...state,
data: null,
error: action.payload,
};
case "DELETE_DATA_REQUEST":
return {
...state,
data: null,
error: null,
};
default:
return state;
}
};
export default dataReducer;
Sagas:
In the sagas/index.js file, you can define your sagas. Sagas are generator functions that watch for specific actions and perform asynchronous operations.
JavaScript
// sagas/index.js
import { takeEvery, put, call } from "redux-saga/effects";
import * as actions from "../actions";
// Simulate an API call
const fetchDataFromAPI = async () => {
try {
const response = await fetch(
"https://jsonplaceholder.typicode.com/todos/1"
);
const data = await response.json();
return data;
} catch (error) {
throw error;
}
};
function* fetchData() {
try {
const data = yield call(fetchDataFromAPI);
yield put(actions.fetchDataSuccess(data));
} catch (error) {
yield put(actions.fetchDataFailure(error.message));
}
}
export function* watchFetchData() {
yield takeEvery("FETCH_DATA_REQUEST", fetchData);
}
Connecting Redux Saga to Your App:
In your index.js file, set up the Redux store with middleware to include Redux Saga.
JavaScript
import React from "react";
import ReactDOM from "react-dom/client";
import "./index.css";
import App from "./App";
import reportWebVitals from "./reportWebVitals";
import { configureStore } from "@reduxjs/toolkit";
import { Provider } from "react-redux";
import createSagaMiddleware from "redux-saga";
import rootReducer from "./reducers";
import { watchFetchData } from "./sagas";
const sagaMiddleware = createSagaMiddleware();
const store = configureStore({
reducer: rootReducer,
middleware: (getDefaultMiddleware) =>
getDefaultMiddleware().concat(sagaMiddleware),
});
sagaMiddleware.run(watchFetchData);
const root = ReactDOM.createRoot(
document.getElementById("root")
);
root.render(
<Provider store={store}>
<React.StrictMode>
<App />
</React.StrictMode>
</Provider>
);
// If you want to start measuring performance in
// your app, pass a function to log results
// (for example: reportWebVitals(console.log))
// or send to an analytics endpoint.
Using Redux Saga in Components:
Now, you can use Redux Saga in your components to trigger asynchronous actions. In your components/MyComponent.js file:
JavaScript
//components/myComponents.js
import React, { useEffect } from "react";
import { useDispatch, useSelector } from "react-redux";
import {
fetchDataRequest,
deleteDataRequest,
} from "../actions";
const MyComponent = () => {
const dispatch = useDispatch();
const data = useSelector((state) => state.data);
const error = useSelector((state) => state.error);
useEffect(() => {
dispatch(fetchDataRequest());
}, [dispatch]);
const handleDeleteData = () => {
dispatch(deleteDataRequest());
};
return (
<div className="app-container">
<h1>Redux Saga App</h1>
<div className="data-container">
{data ? (
<div className="data">
{JSON.stringify(data)}
</div>
) : (
<div className="loading">
{error
? `Error: ${error}`
: "Loading data..."}
</div>
)}
</div>
<button
className="fetch-button"
onClick={() => dispatch(fetchDataRequest())}
>
Fetch Data
</button>
<button
className="delete-button"
onClick={handleDeleteData}
>
Delete Data
</button>
</div>
);
};
export default MyComponent;
App.js and App.css
CSS
/* App.css */
.app-container {
text-align: center;
margin: 20px;
padding: 20px;
border: 1px solid #ccc;
border-radius: 5px;
background-color: #f8f8f8;
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}
h1 {
font-size: 24px;
margin-bottom: 20px;
}
.data-container {
margin: 20px 0;
}
.data {
font-size: 16px;
background-color: #e0e0e0;
padding: 10px;
border-radius: 5px;
}
.loading {
font-size: 16px;
color: #777;
padding: 10px;
}
.fetch-button {
background-color: #007bff;
color: #fff;
padding: 10px 20px;
font-size: 16px;
border: none;
border-radius: 5px;
cursor: pointer;
}
.fetch-button:hover {
background-color: #0056b3;
}
.delete-button {
background-color: #dc3545;
color: #fff;
padding: 10px 20px;
font-size: 16px;
border: none;
border-radius: 5px;
cursor: pointer;
margin-top: 10px;
}
.delete-button:hover {
background-color: #c82333;
}
JavaScript
import "./App.css";
import MyComponent from "./components/myComponent";
function App() {
return <MyComponent />;
}
export default App;
Step 4: use npm command to run the application and output will be on http://localhost:3000/
npm start
Output:
Similar Reads
React Tutorial React is a powerful JavaScript library for building fast, scalable front-end applications. Created by Facebook, it's known for its component-based structure, single-page applications (SPAs), and virtual DOM,enabling efficient UI updates and a seamless user experience.Note: The latest stable version
7 min read
React Fundamentals
React IntroductionReactJS is a component-based JavaScript library used to build dynamic and interactive user interfaces. It simplifies the creation of single-page applications (SPAs) with a focus on performance and maintainability.React.jsWhy Use React?Before React, web development faced issues like slow DOM updates
7 min read
React Environment SetupTo run any React application, we need to first setup a ReactJS Development Environment. In this article, we will show you a step-by-step guide to installing and configuring a working React development environment.Pre-requisite:We must have Nodejs installed on our PC. So, the very first step will be
3 min read
React JS ReactDOMReactDom is a core react package that provides methods to interact with the Document Object Model or DOM. This package allows developers to access and modify the DOM. Let's see in brief what is the need to have the package. Table of ContentWhat is ReactDOM ?How to use ReactDOM ?Why ReactDOM is used
3 min read
React JSXJSX stands for JavaScript XML, and it is a special syntax used in React to simplify building user interfaces. JSX allows you to write HTML-like code directly inside JavaScript, enabling you to create UI components more efficiently. Although JSX looks like regular HTML, itâs actually a syntax extensi
6 min read
ReactJS Rendering ElementsIn this article we will learn about rendering elements in ReactJS, updating the rendered elements and will also discuss about how efficiently the elements are rendered.What are React Elements?React elements are the smallest building blocks of a React application. They are different from DOM elements
3 min read
React ListsReact Lists are used to display a collection of similar data items like an array of objects and menu items. It allows us to dynamically render the array elements and display repetitive data.Rendering List in ReactTo render a list in React, we will use the JavaScript array map() function. We will ite
5 min read
React FormsForms are an essential part of any application used for collecting user data, processing payments, or handling authentication. React Forms are the components used to collect and manage the user inputs. These components include the input elements like text field, check box, date input, dropdowns etc.
5 min read
ReactJS KeysA key serves as a unique identifier in React, helping to track which items in a list have changed, been updated, or removed. It is particularly useful when dynamically creating components or when users modify the list. In this article, we'll explore ReactJS keys, understand their importance, how the
5 min read
Components in React
React ComponentsIn React, React components are independent, reusable building blocks in a React application that define what gets displayed on the UI. They accept inputs called props and return React elements describing the UI.In this article, we will explore the basics of React components, props, state, and render
4 min read
ReactJS Functional ComponentsIn ReactJS, functional components are a core part of building user interfaces. They are simple, lightweight, and powerful tools for rendering UI and handling logic. Functional components can accept props as input and return JSX that describes what the component should render.What are Reactjs Functio
5 min read
React Class ComponentsClass components are ES6 classes that extend React.Component. They allow state management and lifecycle methods for complex UI logic.Used for stateful components before Hooks.Support lifecycle methods for mounting, updating, and unmounting.The render() method in React class components returns JSX el
4 min read
ReactJS Pure ComponentsReactJS Pure Components are similar to regular class components but with a key optimization. They skip re-renders when the props and state remain the same. While class components are still supported in React, it's generally recommended to use functional components with hooks in new code for better p
4 min read
ReactJS Container and Presentational Pattern in ComponentsIn this article we will categorise the react components in two types depending on the pattern in which they are written in application and will learn briefly about these two categories. We will also discuss about alternatives to this pattern. Presentational and Container ComponentsThe type of compon
2 min read
ReactJS PropTypesIn ReactJS PropTypes are the property that is mainly shared between the parent components to the child components. It is used to solve the type validation problem. Since in the latest version of the React 19, PropeTypes has been removed. What is ReactJS PropTypes?PropTypes is a tool in React that he
5 min read
React Lifecycle In React, the lifecycle refers to the various stages a component goes through. These stages allow developers to run specific code at key moments, such as when the component is created, updated, or removed. By understanding the React lifecycle, you can better manage resources, side effects, and perfo
7 min read
React Hooks
Routing in React
Advanced React Concepts
React Projects