Get Who Cares

Where Home Entertainment Meets the Next-Gen tech

How to use Redux-Saga in a React App

Redux-Saga is a layer on Redux that makes it easy to write sagas. I’ll show you how to use this library in a React app and walk through the benefits of using sagas.

React is a popular JavaScript library for building interactive web applications. Redux-Saga is an implementation of the Reactive Programming pattern which makes it easy to implement asynchronous communication between apps, reducing server strain and improving user experience. This tutorial shows how to use both in a React application from scratch.Redux-Saga is a state management solution for React that uses the Saga pattern. Using Redux with sagas allows you to manage your application’s data in functional, predictable ways. This tutorial will show how to use redux and saga together in an app

The “react-redux-saga” is a library that allows users to use Redux in their React apps. It is a one of the most popular libraries for using Redux with React, and it has been used by companies like Facebook.

It is simpler to create web apps using just the React library. However, when the program grows in size, we will need a state-management solution. The Context API in the React library is ideal for globally initializing states and functions in our project. A third-party state-management solution, Redux, also offers us greater control over our state management. However, middlewares like as Redux-Thunk, Redux-Saga, and others are required to manage Redux’s side effects. We’ll go through how to integrate or utilize Redux-Saga in a React project in this article. As an example, we’ll create a basic blog.

Prerequisites

The reader should be familiar with the following technologies in order to follow this article:-

  • ES6 JavaScript
  • The library for React.js
  • In a React project, using Bootstrap
  • The fundamentals of the Redux state-management technology

What we will discover

We will learn the following things in this article:-

  • What exactly is Redux-Saga?
  • To create a React project, follow these steps.
  • Incorporating Bootstrap (react-bootstrap) into our application
  • Multiple route creation (act as pages)
  • Component creation in a React app
  • Redux-Saga integration in our app
  • Using APIs from other parties
  • Putting together a React Reduxt-Saga project

What is Redux-Saga, exactly?

Redux-Saga is a middleware that deals with Redux’s side effects. We may be perplexed by the term “side effect.”

What is the definition of a side effect?

When an action is sent, some state is updated in the standard redux flow. However, in order to execute real-world use cases, we may need to utilize APIs, access local data, and modify states based on the findings. These are referred to as adverse effects.

Only an action dispatch may alter the state of Redux. However, there are instances when we need to use APIs or access local data before we can change the state. These are referred to as adverse effects.

What is the best way to deal with side effects?

We may eliminate these side effects by combining pure redux with middlewares such as redux-thunk, redux-saga, and others.

We’re talking about the Redux-Saga in this post, not the Redux-Thunk.

In a React app, how to utilize Redux-Saga

Let’s get started learning how to integrate Redux-Saga into a React project. In this tutorial, we’ll create a basic blog using React and Redux-Saga. So that we can understand the file structure and processes involved in developing a large-scale program.

Concerning the app that we are going to create

We’ll obtain the list of posts via a third-party API and display it as cards on the main page. Each post’s click will take us to a new page that shows the single post.

We may also go to the home page by clicking the title in the Navigation bar.

The GIF below will give us an idea of how the software works.

How-to-use-Redux-Saga-in-a-React-App

I’m also including the app’s entire file structure so you can have a better idea of what we’re working on.

1633688929_772_How-to-use-Redux-Saga-in-a-React-App

So let’s get started developing the app from the ground up.

Make a brand new React project.

Setting up a React application on your PC is the first step. Using the NPX tool, this is simple to do.

So, first install Node.js on your PC and then use NPX to build a react application. Don’t be alarmed by the name NPX; it’s an utility that comes with NPM (Node Package Manager) 5.2+ and will install alongside Node.js on your machine.

Use the following links for further information on how to install React on your system.

React is available for Windows, Ubuntu, and macOS.

react-redux-saga-example-blog npx create-react-app

This command will build a react application named react-redux-saga-example-blog in the react-redux-saga-example-blog project.

Now launch the program by going to the project directory.

npm start react-redux-saga-example-blog

It will launch the React application we built with the URL https://localhost:3000 in our browser window. If 3000 is busy, the port may change.

1618926588_500_Create-a-Memorize-Word-Game-App-in-React-%E2%86%90

We may now modify our project using our preferred code editor. Visual Studio Code is highly recommended by me.

Boostrap should be included into our app.

For integrating Bootstrap into our React project, we use the react-boostrap package.

With the commands below, we can install the packages React-bootstrap and Bootstrap in our project.

install react-bootstrap@next bootstrap@5.1.1 npm install react-bootstrap@next bootstrap@5.1.1 npm install react-bootstrap@

Now, in the index.js file, import boostrap.min.css.

/ import “bootstrap/dist/css/bootstrap.min.css” in index.js;

Within our React project, we can now utilize React-bootstrap components.

Add some SCSS styles that are unique to you.

Our program will also include custom-style files (SCSS). However, before we can build the SCSS styles, we must first install the node-sass package. So, in our app, install the supported version 4.14.1 of node-sass.

node-sass@4.14.1 npm install

Put your styles in the /assets/scss/style.scss file now.

This style file must also be imported into the index.js file.

/ import “./assets/scss/style.scss” in index.js;

Putting the various paths into action

In our app, we’ll require two pages. The home page will display a list of postings, while another page will display a single post.

Route Page that corresponds
/ Home page
/:id Post page

The /:id refers to a dynamic route in which the post id, such as /1, /2, /3, and so on, must be replaced.

The matching single post will be retrieved from the API using this id.

The react-router-dom package is required to build many routes or pages in a react app.

react-router-dom npm

In the index.js file, import the BrowserRouter component from the react-router-dom package.

js/index.html BrowserRouter is imported from “react-router-dom”;

Wrap the whole project with the BrowserRouter component as well.

js/index.html

Inside the App.js file, we must specify the routes and their associated route components.

/ /> /> /> /> /> /> /> /> /> /> /> />

The Navigation component, Home component, and SinglePost component will be coded later.

As a result, the whole App.js file is provided below.

Create a top navigation menu.

In our app, we’ll require a top navigation bar with a title section, where selecting the title will take us to the home page.

Create a.env file.

I’m creating a.env file to keep track of the API URL. It’s important to remember that changing the.env file requires restarting the program.

REACT APP APP URL=”https://jsonplaceholder.typicode.com” REACT APP APP URL=”https://jsonplaceholder.typicode.com”

Part of the Redux-Saga

With the exception of redux-saga, almost all functionalities are integrated in our app. You will have a better grasp of the next stages if you have previously worked with Redux projects.

Set up the shop and wrap the app in Provider.

To begin, create a store and wrap the whole app with a Provider component, passing the store as a prop. For a Redux project, this is standard.

Create a directory called store and a file called index.js within it.

Reducers and the sagas described in this file will be discussed later.

Now, in our index.js file, import the newly generated file and Provider component.

Import store from “./store” and Provider from “react-redux”

Wrap the program with the Provider component and provide the store as a parameter.

As a result, the whole index.js file should look like this.

Define the kinds of activities and the acts themselves.

We must first define the action categories before we can define the actions. The action types are used to find the reducer that corresponds to the action. Let’s start with the action kinds.

We’ll just be working with posts in this tutorial, so create a directory called posts within the store and add the actionTypes.js file to it.

It’s worth noting that in this file, we’re just assigning the action type strings to variables so that they can be easily imported into actions, reducers, and saga.

Import these variables into the /store/posts/actions.js action file.

GET POSTS, GET POSTS SUCCESS, GET POSTS FAIL, GET POST DETAILS, GET POST DETAILS SUCCESS, GET POST DETAILS FAIL, GET POST DETAILS FAIL, GET POST DETAILS SUCCESS, GET POST DETAILS FAIL, GET POST

Define all post-related activities inside it as well.

getPosts = () => export const getPosts = () => export const getPostsSuccess = (posts) => getPostsSuccess = (posts) => getPostsSuccess = (posts) => getPostsSuccess = (posts) => getPostsSuccess = (posts) => getPosts export const getPostsFail = (error) => return type: GET POSTS SUCCESS, payload: posts,; GET POSTS FAIL, payload: error, return type: GET POSTS FAIL,…

The action getPosts() is sent shortly after the component is mounted when we load the home page.

It then proceeds to the appropriate action, reducer, and saga, where it gets the posts from the API and dispatches the getPostsSucces() action if the saga response is successful, or getPostsFail() if the saga answer is a failure.

The whole actions.js file will be identical to what is shown below.

Part of the Reducer

Make a reducer.js file in the /store/posts directory. Import all of the previously specified action types.

GET POSTS, GET POSTS SUCCESS, GET POSTS FAIL, GET POST DETAILS, GET POST DETAILS SUCCESS, GET POST DETAILS FAIL, GET POST DETAILS FAIL, GET POST DETAILS SUCCESS, GET POST DETAILS FAIL, GET POST

Now it’s time to set up the states for the postings.

initialState = posts: [], post:, loadingPosts: false, loadingPostDetails: false, error: message: “”,,; initialState = posts: [], post:, loadingPosts: false, loadingPostDetails: false, error: message: “”,

Define the PostReducer now.

(state = initialState, action) => const PostReducer = (state = initialState, action) => switch (action.type) case GET POSTS: state =…state, loadingPosts: true; break; case GET POSTS SUCCESS: state =…state, posts: action.payload, loadingPosts: false; break; case GET POSTS FAIL: state =…state, error: loadingPosts: false; break; case GET POSTS SUCCESS: state =…state, error: loadingPosts: false; break; case break;… default: state =…state; break; return state;

The reducer file as a whole looks like this.

The Saga part is being coded.

The takeLatest, put, and call APIs from redux-saga/effects must be imported.

You may be perplexed by some of the terminology used here. I’ll explain them to you.

  1. call: This method creates an Effect description that tells the middleware to call the function fn with the parameters args.
  2. put: Creates an Effect description that tells the middleware when action should be sent to the store.
  3. Yield: The yield keyword stops the execution of a generator function, and the value of the expression after it is returned to the generator’s caller.
  4. takeLatest: On each action sent to the Store that matches pattern, forks a saga. If any prior saga job is still running, it will be immediately cancelled.

There are APIs such as takeEvery, takeMaybe, and others in addition to takeLatest.

You can learn more about effect makers in the Saga documentation.

import takeLatest, put, call from “redux-saga/effects”; import GET POSTS,… from “./actionTypes”; import getPostsSuccess, getPostsFail,… from “./actions”; import getPosts, getPostDetails from “../../helpers/backend helper”; import GET POSTS,… from “./actions”; import GET POSTS … export default CartSaga; function* onGetPosts() try const response = yield call(getPosts); yield put(getPostsSuccess(response)); catch (error) yield put(getPostsFail(error.response)); function* CartSaga() yield takeLatest(GET POSTS, onGetPosts);

That concludes the story. The js file looks like this.

Create a saga file and a common reducers file.

For the posts, we built a reducer and a saga. These will need to be imported into common reducers and sagas files.

So, let’s go to work on the reducers. First, let’s look at the js file.

Create the sagas.js file as shown below.

Organizing the assistants

We can observe that certain files are imported as helpers from the preceding files. Take a look at these documents.

To begin, create a file called url helper.js in the helpers directory. This is just a list of all of our API’s routes.

Now, within the same helpers directory, create a file called api helper.js. All of the functions for making API calls using the axios package will be defined here.

Finally, we create a file called backend helper.js in the directory, which is immediately imported into our saga file.

You will grasp the reasoning if you are familiar with basic JS.

Components or pages of the route are coded.

In the App.js file, we defined two routes: / and /:id, and now the / route returns the Home component while the /:id route provides the SinglePost component.

Let us now define these two elements. Despite the fact that they are components, we have placed them in the pages directory since they seem to be pages.

Create a Home component in the pages directory.

We’ll import the react-redux package’s useDispatch action and the actions file’s getPosts action.

import “react-reduxuseDispatch; “‘s import “../store/posts/actionsgetPosts; “‘s import “../store/posts/actionsgetPosts; “‘s import “../store/posts/actionsgetPosts; “‘s import “../store/posts/actions”‘

After the component has been installed, we can now dispatch the operation getPosts.

useEffect(() => dispatch(getPosts());, []); let dispatch = useDispatch(); useEffect(() => dispatch(getPosts());, []);

The whole Home component will be the same as what is seen below.

We’ll make a singlePost component in the similar way. The URL parameter values are obtained using useParams from react-router-dom.

useParams is imported from “react-router-dom”;

If there is a change in params.id, we call the method getPostDetails(params.id).

useEffect(() => dispatch(getPostDetails(params.id));, [params.id]); let params = useParams(); useEffect(() => dispatch(getPostDetails(params.id));, [params.id]);

The component used to display a single post will be the same as the one shown below.

Component for displaying the posts

We’re using react-useSelector redux’s API to retrieve the posts from the reducer.

export default function Posts() const posts, loadingPosts = useSelector((state) => state.PostReducer);… import useSelector from “react-redux”; import Loader from “react-loader-spinner”; export default function Posts() const posts, loadingPosts = useSelector((state) => state.PostReducer);…

The posts component will be the same as in the example below.

Component for displaying a single post

We access the state post from the reducer in the same manner.

useSelector((state) => state.PostReducer); const post, loadingPostDetails = useSelector((state) => state.PostReducer);

Below is the PostDetails component.

Codesandbox

To see the live app, go to the CodeSandbox link. You can also clone this project and modify the code in your CodeSandbox account.

GitHub

You may always clone this project, refer to the code, and work on top of it by going to the GitHub repository.

https://github.com/techomoro/react-redux-saga-example-blog

Summary

Using a basic blog as an example, we went through how to integrate or utilize Redux-Saga in a React project. We built a large-scale react application using the identical file structure. Because Redux-Saga is often used for large-scale purposes.

As an example:

As if Loading…

This may be interesting to you.

The “redux-saga post request example” is a tutorial on how to use Redux-Saga in a React app. It will show you how to make asynchronous requests with the Saga pattern.

{“@context”:”https://schema.org”,”@type”:”FAQPage”,”mainEntity”:[{“@type”:”Question”,”name”:”How do you use redux in react application?”,”acceptedAnswer”:{“@type”:”Answer”,”text”:”A: The redux library provides a way to manage application state. In order to use this, you need to install the library and add it as a dependency in your projects package.json file or create an object that has methods for managing store state instead of just writing out all of your data on every render call.”}},{“@type”:”Question”,”name”:”How do I use Redux Redux saga?”,”acceptedAnswer”:{“@type”:”Answer”,”text”:”A: To use the Redux Saga, you must first download and install it from your VR headsets online store.”}},{“@type”:”Question”,”name”:”How Saga works in react?”,”acceptedAnswer”:{“@type”:”Answer”,”text”:”A: Saga uses a server side rendering engine to generate the DOM, which is then updated after each step.”}}]}

Frequently Asked Questions

How do you use redux in react application?

A: The redux library provides a way to manage application state. In order to use this, you need to install the library and add it as a dependency in your projects package.json file or create an object that has methods for managing store state instead of just writing out all of your data on every render call.

How do I use Redux Redux saga?

A: To use the Redux Saga, you must first download and install it from your VR headsets online store.

How Saga works in react?

A: Saga uses a server side rendering engine to generate the DOM, which is then updated after each step.

Related Tags

  • redux-saga tutorial
  • react redux-saga example
  • redux-saga hooks
  • redux-saga vs redux-thunk
  • redux-saga/effects