DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Because the DevOps movement has redefined engineering responsibilities, SREs now have to become stewards of observability strategy.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Related

  • The Complete Tutorial on the Top 5 Ways to Query Your Relational Database in JavaScript - Part 2
  • Implementation of the Raft Consensus Algorithm Using C++20 Coroutines
  • What Are Events? Process, Data, and Application Integrators
  • Building Angular Library and Publishing in npmjs Registry

Trending

  • Introducing Graph Concepts in Java With Eclipse JNoSQL, Part 3: Understanding Janus
  • The Ultimate Guide to Code Formatting: Prettier vs ESLint vs Biome
  • How Large Tech Companies Architect Resilient Systems for Millions of Users
  • Navigating Double and Triple Extortion Tactics
  1. DZone
  2. Culture and Methodologies
  3. Career Development
  4. React, Redux and Saga: Connecting the Dots

React, Redux and Saga: Connecting the Dots

We look at how to implement microservices architectural patterns on the front-end using React, Redux, and the saga pattern.

By 
Aruna Karunarathna user avatar
Aruna Karunarathna
·
Jan. 28, 19 · Tutorial
Likes (5)
Comment
Save
Tweet
Share
11.1K Views

Join the DZone community and get the full member experience.

Join For Free

"Viewer discretion advised." This article is written by a person who is very new to front-end programming with React and worked on backend development for a number of years. I’m quite fascinated, however, by UI recently, since UI libraries are adopting some of the distributed computing theories/features used in middleware applications.

If you have worked with Angular, passing state within components is not as clean as you would have liked. In my personal opinion, React handled the situation quite delicately using React-Redux, a centralized big static state object, which was shared within the whole application, and react-saga, a library which handles the application side effects, e.g. asynchronous actions. In this tutorial, we will build a React application which uses the Redux and the saga pattern. 

I will try to explain how the component interaction and state update works by using the sample I prepared for this post. The sample app is pretty straight forward. It has a button which fetches all the users by executing a remote API call. See the below diagram for a visualization:

This is the simple workflow theory behind event dispatching, remote data fetching, state changes, and propagating those changes to the UI. This cycle continues until the lifecycle of the component ends.

A. Denotes the UI action which resulted in a dispatch event. Below is some sample code that fires up a dispatch event with the event name and the data used for the event. In this example, we dispatch a UI event to fetch the users list. So we dispatch an event of type FETCH_USERS.

const mapDispatchToProps = (dispatch) => {
    return {
        fetchUsers : () => {
            dispatch({
                type: 'FETCH_USERS'
            })
        }};};

B. We have an API call defined to get all user data, from a mockable URL: http://demo7507024.mockable.io/react-sample. When the FETCH_USERS event got fired, there was a user saga listening for this type of event, and it fired up the  UserApi.getUsers() method. After receiving the data, it fired up another event to update the store. See the below code snippet in the UserSaga.js file:

//Fetching the users list
const response = yield call(UserApi.getUsers);

// Then instructing the middleware to action to update the store.
        yield put({
            type: ACTION_TYPES.UI_ACTION.ON_USERS_DATA,
            data: response.data
        });

In UserSaga.js, we have defined the takeEvery(pattern, saga, ...args), so whenever it matches the ‘FETCH_USERS’ pattern, it will dispatch the event, to update the store. With each call it will construct a new task for the matching event.

An application can have multiple sagas’s based on the requirement, so we pile them into one main saga, as in the MainSaga.js file.

C. Now comes to the store update section, as you saw on the step ‘B’ there is a new event fired to update the redux store, which is ‘ON_USERS_DATA’, so we have to catch that event and update the state change. For that we used the UserReducer.js

export default function userReducer(state = initialState, action) {
    switch (action.type) {
        case ACTION_TYPES.UI_ACTION.ON_USERS_DATA:
            return Object.assign({}, state, {userList: action.data});
        default:
            return state;
    }
}

Here we have updated the userList in the store object with the new data. Now the update of the Redux store is complete.

D. Now we have to listen to that state update and handle the UI update in the render method, inside the component. We will receive the update to the component via the mapStateToProps method.

const mapStateToProps = (state) => {
    return {
        users: state.userActions.userList
    };
};

Now, the newly fetched user list is visible to the UI. So now you have connected the dots between React, Redux, and redux-saga. I hope you have gained some idea of how the component interactions work and don’t forget to comment on your thoughts as well.

Source code for this sample can be found here. https://github.com/arunasujith/react-redux-saga-sample. You can also try to create the project from scratch. First, install the create-react-app using he below command.

npm i -g create-react-app

Now create a sample project.

create-react-app react-redux-saga-sample

Run the project using:

npm start

Commands to install the various React libraries.

npm install --save axios
npm install --save redux
npm install --save redux-saga
npm install --save react-redux
React (JavaScript library) Event application Distributed Computing Data (computing) code style workplace Library Interaction

Published at DZone with permission of Aruna Karunarathna, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • The Complete Tutorial on the Top 5 Ways to Query Your Relational Database in JavaScript - Part 2
  • Implementation of the Raft Consensus Algorithm Using C++20 Coroutines
  • What Are Events? Process, Data, and Application Integrators
  • Building Angular Library and Publishing in npmjs Registry

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!