Close Menu
Soshace Digital Blog

    Subscribe to Updates

    Get The Latest News, Updates, And Amazing Offers

    What's Hot
    Content & Leadership

    Analyzing Storytelling’s Impact on Content Marketing Effectiveness

    Startups

    Why Startups Fail? Part 2

    Consultation

    Best Background Check Services Assessments

    Important Pages:
    • Home
    • About
    • Services
    • Contact Us
    • Privacy Policy
    • Terms & Conditions
    Facebook X (Twitter) Instagram LinkedIn YouTube
    Today's Picks:
    • Scaling Success: Monitoring Indexation of Programmatic SEO Content
    • Leveraging Influencers: Key Drivers in New Product Launches
    • How Privacy-First Marketing Will Transform the Industry Landscape
    • The Impact of Social Proof on Thought Leadership Marketing
    • Balancing Value-Driven Content and Promotional Messaging Strategies
    • Top Influencer Marketing Platforms to Explore in 2025
    • Emerging Trends in Marketing Automation and AI Tools for 2023
    • Strategies to Mitigate Duplicate Content in Programmatic SEO
    Wednesday, September 10
    Facebook X (Twitter) Instagram LinkedIn YouTube
    Soshace Digital Blog
    • Home
    • About
    • Services
    • Contact Us
    • Privacy Policy
    • Terms & Conditions
    Services
    • SaaS & Tech

      Maximizing Efficiency: How SaaS Lowers IT Infrastructure Costs

      August 27, 2025

      Navigating Tomorrow: Innovations Shaping the Future of SaaS

      August 27, 2025

      Maximizing Impact: Strategies for SaaS & Technology Marketing

      August 27, 2025
    • AI & Automation

      Enhancing Customer Feedback Analysis Through AI Innovations

      August 27, 2025

      Navigating the Impact of AI on SEO and Search Rankings

      August 27, 2025

      5 Automation Hacks Every Home Service Business Needs to Know

      May 3, 2025
    • Finance & Fintech

      Critical Missteps in Finance Marketing: What to Avoid

      August 27, 2025

      Analyzing Future Fintech Marketing Trends: Insights Ahead

      August 27, 2025

      Navigating the Complex Landscape of Finance and Fintech Marketing

      August 27, 2025
    • Legal & Compliance

      Exploring Thought Leadership’s Impact on Legal Marketing

      August 27, 2025

      Maximizing LinkedIn: Strategies for Legal and Compliance Marketing

      August 27, 2025

      Why Transparency Matters in Legal Advertising Practices

      August 27, 2025
    • Medical Marketing

      Enhancing Online Reputation Management in Hospitals: A Guide

      August 27, 2025

      Analyzing Emerging Trends in Health and Medical Marketing

      August 27, 2025

      Exploring Innovative Content Ideas for Wellness Blogs and Clinics

      August 27, 2025
    • E-commerce & Retail

      Strategic Seasonal Campaign Concepts for Online and Retail Markets

      August 27, 2025

      Emerging Trends in E-commerce and Retail Marketing Strategies

      August 27, 2025

      Maximizing Revenue: The Advantages of Affiliate Marketing for E-Commerce

      August 27, 2025
    • Influencer & Community

      Leveraging Influencers: Key Drivers in New Product Launches

      August 27, 2025

      Top Influencer Marketing Platforms to Explore in 2025

      August 27, 2025

      Key Strategies for Successful Influencer Partnership Negotiations

      August 27, 2025
    • Content & Leadership

      The Impact of Social Proof on Thought Leadership Marketing

      August 27, 2025

      Balancing Value-Driven Content and Promotional Messaging Strategies

      August 27, 2025

      Analyzing Storytelling’s Impact on Content Marketing Effectiveness

      August 27, 2025
    • SEO & Analytics

      Scaling Success: Monitoring Indexation of Programmatic SEO Content

      August 27, 2025

      Strategies to Mitigate Duplicate Content in Programmatic SEO

      August 27, 2025

      Effective Data Visualization Techniques for SEO Reporting

      August 27, 2025
    • Marketing Trends

      How Privacy-First Marketing Will Transform the Industry Landscape

      August 27, 2025

      Emerging Trends in Marketing Automation and AI Tools for 2023

      August 27, 2025

      Maximizing ROI: Key Trends in Paid Social Advertising

      August 27, 2025
    Soshace Digital Blog
    Blog / JavaScript / React / React Lessons / React Lesson 13. Part 1: Asynchronous actions
    JavaScript

    React Lesson 13. Part 1: Asynchronous actions

    Mohammad Shad MirzaBy Mohammad Shad MirzaJuly 3, 2020Updated:July 3, 2020No Comments5 Mins Read
    Facebook Twitter Pinterest Telegram LinkedIn Tumblr Email Reddit
    React Lesson 13. Part 1: Asynchronous actions
    React Lesson 13. Part 1: Asynchronous actions
    Share
    Facebook Twitter LinkedIn Pinterest Email Copy Link
    React Lesson 13. Part 1: Asynchronous actions
    React Lesson 13. Part 1: Asynchronous actions

    Hey everyone, we are going to learn asynchronous actions in this lesson. Up until now, we were using fixtures.js to get the articles and comments and our actions were pure functions, which worked fine. But now we will get our data from an API endpoint just like what happens in the real world.
    Previous lessons you can find by the link.

    API calls are asynchronous, it means that there will be a small delay followed by success or failure of an API request. We are going to learn how to handle all these cases. Let’s start.

    Setup

    If you go to the repo, you will see a simple API already setup. Go into simple_api directory and run:

    npm install

    OR

    npm install

    This will install all the required packages and you will see a node_modules folder created for you.
    Now, we have run the server and development server simultaneously as one will serve the requests yarn run API and the other one launches dev server for our app yarn start.
    API and dev server both are running on different ports. We have to set up redirection to avoid any сrossdomain requests. Everything that goes to /API will be proxied to your API. It is now localhost:3001, but later it can be some remote address. You set up redirection and will have access to the article from both addresses:

    http://localhost:3001/api/article

    http://localhost:8080/api/article

    Let’s start working on the implementation of API, we don’t want to keep using fixtures.js with static data.
    At the moment, the api/article is returning all the articles. We need to limit the number of articles returned in one request as the number can be huge and we might not need everything at first. Moreover, we will make additional requests to get comments separately.

    The Concept: How it works?

    First, let us get a list of articles from API and get them displayed at our traditional address:

    Read More:  Introduction to WebAssembly: The Magic of Native Code in Web Apps

    http://localhost:8080

    We will use fetch to call request API for articles. Any asynchronous API call can include three important phases that we need to address. We will see what are those and how to handle them using plain old synchronous action creators:

    • Start of request

      The first phase is when we start fetching data. We need to tell UI that data fetching has been started. We can do this by dispatching an action with a flag isFetching: true and then showing a loader/spinner based on this state.

    • Request finished successfully

      The second phase occurs when the request is completed successfully and we have the desired data in API response. We can then dispatch an action with data as payload and reset the flag isFetching to false. This will hide the spinner and render the data.

    • Request failed

      The third phase occurs when the request is failed and we don’t have the data to render. In this case, we have to inform the user that something bad has happened and we have met an error. We can dispatch an action with an error message and reset the flag isFetching to false. This will hide the spinner and show the error message.

    Note: Only one phase from phase 2 or 3 happens in any API call. Requests will either be successful or failed.

    Let’s code

    We have already seen that we will need three types of action creator to handle all 3 cases. These can be defined in types.js as:

    export const FETCH_ARTICLE_REQUEST = "fetch_article_request";
    export const FETCH_ARTICLE_SUCCESS = "fetch_article_success";
    export const FETCH_ARTICLE_FAILURE = "fetch_article_failure";

    We will use fetch API in the examples. We have to install to redux-thunk to be able to dispatch asynchronous actions.

    yarn add redux-thunk

    Actions must return a pure object, which means we can’t wait for an API to return response and we dispatch an action afterward. That’s where redux-thunk comes into play. Redux Thunk is a middleware that allows us to return a function instead of an object. The inner function receives the store methods dispatch as parameters that we can use to delay the dispatch of action or dispatch only if a certain condition is met. Let’s add this middleware to store:

    const enhancer = compose(
      applyMiddleware(randomId, ReduxThunk),
      window.devToolsExtension ? window.devToolsExtension() : f => f
    );
    // other demo middleware are removed to simplify code // we only need these two middleware

    Now we have to create the three action creators for each phase we talked earlier:

    import { FETCH_ARTICLE_REQUEST, FETCH_ARTICLE_SUCCESS, FETCH_ARTICLE_FAILURE } from "../types";
    import fetch from 'cross-fetch';
    
    const requestStart = () => {
      return {
        type: FETCH_ARTICLE_REQUEST,
      };
    };
    
    const requestSuccess = (data) => {
      return {
        type: FETCH_ARTICLE_SUCCESS,
        payload: data,
      };
    };
    
    const requestFailed = (err) => {
      return {
        type: FETCH_ARTICLE_FAILURE,
        err: err,
      };
    };
    
    export const fetchArticleRequest = () => {
      return function (dispatch) {
        // First dispatch: the app state is updated to inform
        // that the API call is starting.
    
        dispatch(requestStart());
    
        // The function called by the thunk middleware can return a value,
        // that is passed on as the return value of the dispatch method.
    
        // In this case, we return a promise to wait for.
        // This is not required by thunk middleware, but it is convenient for us.
    
        return fetch(`api/articles`)
          .then(
            response => response.json()
          )
          .then(json =>
            dispatch(requestSuccess(json))
          )
          .catch(err =>
            dispatch(requestFailed(err))
          );
      }
    };
    

    We can dispatch as many times as we want. As you can see from the code above, we are sending flags in the form of types. We will update the isFetching state as true or false based on the type we receive at reducer which will inform the view about the three phases on API call discussed earlier.

    Finally, we have to handle these actions on the reducer side and then dispatch actions from the view. We will continue with that in the next lesson.

    Lesson code can be found in the GitHub repo.

    Read More:  React Lesson 8: Deep Dive into React Redux
    Share. Facebook Twitter Pinterest LinkedIn Tumblr Email
    Mohammad Shad Mirza
    • X (Twitter)
    • LinkedIn

    JavaScript lover working on React Native and committed to simplifying code for beginners. Apart from coding and blogging, I like spending my time sketching or writing with a cup of tea.

    Related Posts

    Streamlining Resource Allocation for Enhanced Project Success

    December 18, 2024

    Conducting Effective Post-Project Evaluations: A Guide

    December 16, 2024

    Strategies for Keeping Projects on Track and Meeting Deadlines

    December 10, 2024
    Leave A Reply Cancel Reply

    You must be logged in to post a comment.

    Stay In Touch
    • Facebook
    • Twitter
    • Pinterest
    • Instagram
    • YouTube
    • Vimeo
    Don't Miss
    CSS June 24, 2019

    8 Best Bootstrap UI Kits – World’s Most Popular & Free UI Frameworks

    In this article, we’ll cover the best and free (some, though, have paid premium features) Bootstrap UI Kits that you can use as starting points for your designs.

    Building React Components Using Children Props and Context API

    August 22, 2019

    React Lesson 3: Exploring the React Component Lifecycle

    November 14, 2019

    Startup Spotlight: Five Companies That Revolutionize Healthcare & Wellness

    March 12, 2019

    Categories

    • AI & Automation
    • Angular
    • ASP.NET
    • AWS
    • B2B Leads
    • Beginners
    • Blogs
    • Business Growth
    • Case Studies
    • Comics
    • Consultation
    • Content & Leadership
    • CSS
    • Development
    • Django
    • E-commerce & Retail
    • Entrepreneurs
    • Entrepreneurship
    • Events
    • Express.js
    • Facebook Ads
    • Finance & Fintech
    • Flask
    • Flutter
    • Franchising
    • Funnel Strategy
    • Git
    • GraphQL
    • Home Services Marketing
    • Influencer & Community
    • Interview
    • Java
    • Java Spring
    • JavaScript
    • Job
    • Laravel
    • Lead Generation
    • Legal & Compliance
    • LinkedIn
    • Machine Learning
    • Marketing Trends
    • Medical Marketing
    • MSP Lead Generation
    • MSP Marketing
    • NestJS
    • Next.js
    • Node.js
    • Node.js Lessons
    • Paid Advertising
    • PHP
    • Podcasts
    • POS Tutorial
    • Programming
    • Programming
    • Python
    • React
    • React Lessons
    • React Native
    • React Native Lessons
    • Recruitment
    • Remote Job
    • SaaS & Tech
    • SEO & Analytics
    • Soshace
    • Startups
    • Swarm Intelligence
    • Tips
    • Trends
    • Vue
    • Wiki
    • WordPress
    Top Posts

    Anime.js to MP4 and GIF with Node.js and FFMPEG

    Express.js April 25, 2023

    Setting Up Automated Semantic Versioning For Your NodeJS Project

    JavaScript August 8, 2020

    React Native AsyncStorage Example: When I Die App

    JavaScript December 31, 2019

    Introduction to the Best Code Playgrounds: JSFiddle, Codepen, and CodeSandbox

    JavaScript June 19, 2019

    Subscribe to Updates

    Get The Latest News, Updates, And Amazing Offers

    About Us
    About Us

    Soshace Digital delivers comprehensive web design and development solutions tailored to your business objectives. Your website will be meticulously designed and developed by our team of seasoned professionals, who combine creative expertise with technical excellence to transform your vision into a high-impact, user-centric digital experience that elevates your brand and drives measurable results.

    7901 4th St N, Suite 28690
    Saint Petersburg, FL 33702-4305
    Phone: 1(877)SOSHACE

    Facebook X (Twitter) Instagram Pinterest YouTube LinkedIn
    Our Picks
    Entrepreneurship

    Essential Strategies for Building a Robust Entrepreneurial Network

    JavaScript

    Essential Steps for Effective Project Risk Assessment

    Programming

    Best Practices for Writing Clean and Maintainable Code

    Most Popular

    7 Concepts: Why Your SVG Is the Way It Is

    Beginners

    Top React JS Interview Questions

    JavaScript

    Why Localize: Website Translation Best Practices

    Tips
    © 2025 Soshace Digital.
    • Home
    • About
    • Services
    • Contact Us
    • Privacy Policy
    • Terms & Conditions

    Type above and press Enter to search. Press Esc to cancel.