How to use the React Async Library for Declarative Data Fetching

How to use the React Async Library for Declarative Data Fetching

In this tutorial, we explored how to use the React-Async library to help us fetch data easily without any hassle. We also looked at some of the helper functions it offers and the philosophy behind it. React-Async is a powerful tool and has the potential to enhance developer experience.

In this tutorial, we explored how to use the React-Async library to help us fetch data easily without any hassle. We also looked at some of the helper functions it offers and the philosophy behind it. React-Async is a powerful tool and has the potential to enhance developer experience.

Generally, there are two ways of writing code: Imperatively/Declaratively and two ways of fetching Data: Synchronously/Asynchronously. We are more convenient with making requests imperatively using fetch or libraries like axios.

Table of Contents

  • Fetching Data Declaratively with React-Async
  • Helper Components
  • More Helper Functions

With async-await, we get an opportunity to move from imperative asynchronous to imperative synchronous code style for fetching data. React is a library that makes it easy to build UIs declaratively. The key word is declarative. This is why there is a mixed pattern when we have both imperative code (for data fetching) and declarative code (for UI composition).

React-async provides a declarative API to perform any REST API call easily using a single React component. It takes care of handling errors, promise resolution and retrying promises and an excellent job at dealing with local asynchronous state.

Fetching Data Declaratively with React-Async

For better understanding let’s break down our topic into two parts. Declarative data fetching and Asynchronous API Calls in react.

Declarative data fetching is an approach used in calling APIS where you declare what you want it gets done for you without you worrying about all the things related to the call. It’s the opposite of the imperative approach where you also need to detail the steps, i.e. how to get what you need.

Since JavaScript is synchronous by default and is single threaded, when we want to render a component that shows some data coming from an asynchronous call before React 16, we were stuck with classes. We had to use the component lifecycle methods to ensure the call happens when the component is mounted, and then we use the local state to manage the loading state.

Asynchronous requests will wait for a request to respond while the rest of the code continues to execute. Then when the time is right, a callback will spring these asynchronous requests into action.

Let’s demonstrate this by making a call to an endpoint to grab a list of cryptocurrency prices.

import React, { Component } from 'react';
import axios from 'axios';

class App extends Component {
  state = {
    data: [],
    error: '',
  };

  componentDidMount() {     
    axios
      .get('https://api.coinmarketcap.com/v1/ticker/?limit=1')
      .then(res => this.setState({ data: res.data }))
      .catch(error => this.setState({ error }));
  }

  render () {
    return (
      
        {this.state.data.map(el => (* {el.name}: {el.price_usd}
))}
      
    );
  }
}

export default App;

N/B: Install axios by typing ‘npm install axios` in your terminal

Here we make our API call in the componentDidMount function to ensure it runs as soon as the component is loaded. We can make sense of our data only after we go through the following steps:

  • First, we make a request to the API
  • We receive a response
  • We extract data from the response
  • Then store the data in our local state

In the event of an error during the data fetching process:

  • We catch the error
  • Store the data in our local state

As you can see we explicitly spell out how and what to do at every step in fetching the data. Almost every React developer is familiar with the lines of code above. Though the syntax and functions work correctly, the code can be re-written to be more elegant and in fewer lines, if written declaratively. Let’s rewrite it using React Async.

First, you need to install the package by typing npm install react-async in your terminal. Then write your component with the following code:

import React, { Component } from 'react';
import Async from 'react-async';

const loadJson = () =>
  fetch("https://api.coinmarketcap.com/v1/ticker/?limit=1")
    .then(res => (res.ok ? res : Promise.reject(res)))
    .then(res => res.json())

const App = () => (
  
    {({ data, error, isLoading }) => {
      if (isLoading) return "Loading..."
      if (error) return ``Something went wrong: ${error.message}``

      if (data)
        return (
          
             {data.map(el => (
              
                {el.name}: {el.price_usd}
              
             ))}
          
        )

      return null
    }}
  
)

export default App;

However, since we are using CodeSandbox, we will add React-Async from the dependency menu.

Here we have rewritten our component using hooks instead of classes. We first create a function loadJson to handle our data fetching. Then, inside our App component, we utilize the Async component made available through the React Async library.

Once our promise is resolved, props are made available to us to handle different scenario's.

  • isLoading is available so we can display a user-friendly message while the data is yet to be loaded.
  • error is available in case of an error during the fetch.
  • data is the actual data returned after the fetching is complete.

As we can see, we no longer have to use classes or lifecycle methods to load our data neither did we tell React-Async how to process the data or how to update our state.

React Async manages the loading state through the isLoading fallback prop, which is rendered until data is ready to be rendered, that is when the dependent asynchronous call resolves and returns the data.

Helper Components

React Async comes with several helper components that make your JSX more declarative and less cluttered. Each of the helper components will only render its children when appropriate. We can rewrite our App function to look like this:

const App = () => (
  
    Loading...

    
      {data => (
                   
          {data.map(el => (
            
              {el.name}: {el.price_usd}
            
          ))}
        
      )}
    

    
      {error => `Something went wrong: ${error.message}`}
    
  
)

In the example above, we have utilized the **Async.Loading**, **Async.Resolved** and **Async.Rejected** functions to simplify our code and make it more readable. Helper components provided by React-Async can take a React element or a function as children. When you provide a function, you’ll receive render props you can use in your component.

More Helper Functions

Let’s build a small user profile app that utilizes some more helper functions. Update your component to the following code:

import React, { Component } from 'react';
import Async from 'react-async';

const loadUser = ({ userId }) =>
  fetch('`https://reqres.in/api/users/${userId}'`)
    .then(res => (res.ok ? res : Promise.reject(res)))
    .then(res => res.json())

const UserPlaceholder = () => (
  
    User Details Loading

  
)

const UserDetails = ({ data }) => (
  
    
    
      {data.data.first_name} {data.data.last_name}
    
  
)

const App = () => (
    
      
        
      
      {data => }
      {error => 
{error.message}
}
    
)
export default App;

Let’s go over the functions we declared :

  • loadUser - We define this function to handle data fetching. It takes in a prop (userId) and queries the API based on the id**.**
  • userPlaceholder - This is the fallback component that will be displayed when the promise has not yet resolved. (When the data has not finished loading).
  • *userDetails *- This component handles the actual display of the user data. It takes the data in via props and is only rendered when the promise has been resolved.
  • *Finally,_ we utilized the_ **Async.Pending_**,_**_Async.Fulfilled_**and_**Async.Rejected\_* functions to simplify our code and make it more readable.

To learn more check out the docs here.

JavaScript developers should you be using Web Workers?

JavaScript developers should you be using Web Workers?

Do you think JavaScript developers should be making more use of Web Workers to shift execution off of the main thread?

Originally published by David Gilbertson at https://medium.com

So, Web Workers. Those wonderful little critters that allow us to execute JavaScript off the main thread.

Also known as “no, you’re thinking of Service Workers”.

Photo by Caleb Jones on Unsplash

Before I get into the meat of the article, please sit for a lesson in how computers work:

Understood? Good.

For the red/green colourblind, let me explain. While a CPU is doing one thing, it can’t be doing another thing, which means you can’t sort a big array while a user scrolls the screen.

This is bad, if you have a big array and users with fingers.

Enter, Web Workers. These split open the atomic concept of a ‘CPU’ and allow us to think in terms of threads. We can use one thread to handle user-facing work like touch events and rendering the UI, and different threads to carry out all other work.

Check that out, the main thread is green the whole way through, ready to receive and respond to the gentle caress of a user.

You’re excited (I can tell), if we only have UI code on the main thread and all other code can go in a worker, things are going to be amazing (said the way Oprah would say it).

But cool your jets for just a moment, because websites are mostly about the UI — it’s why we have screens. And a lot of a user’s interactions with your site will be tapping on the screen, waiting for a response, reading, tapping, looking, reading, and so on.

So we can’t just say “here’s some JS that takes 20ms to run, chuck it on a thread”, we must think about where that execution time exists in the user’s world of tap, read, look, read, tap…

I like to boil this down to one specific question:

Is the user waiting anyway?

Imagine we have created some sort of git-repository-hosting website that shows all sorts of things about a repository. We have a cool feature called ‘issues’. A user can even click an ‘issues’ tab in our website to see a list of all issues relating to the repository. Groundbreaking!

When our users click this issues tab, the site is going to fetch the issue data, process it in some way — perhaps sort, or format dates, or work out which icon to show — then render the UI.

Inside the user’s computer, that’ll look exactly like this.

Look at that processing stage, locking up the main thread even though it has nothing to do with the UI! That’s terrible, in theory.

But think about what the human is actually doing at this point. They’re waiting for the common trio of network/process/render; just sittin’ around with less to do than the Bolivian Navy.

Because we care about our users, we show a loading indicator to let them know we’ve received their request and are working on it — putting the human in a ‘waiting’ state. Let’s add that to the diagram.

Now that we have a human in the picture, we can mix in a Web Worker and think about the impact it will have on their life:

Hmmm.

First thing to note is that we’re not doing anything in parallel. We need the data from the network before we process it, and we need to process the data before we can render the UI. The elapsed time doesn’t change.

(BTW, the time involved in moving data to a Web Worker and back is negligible: 1ms per 100 KB is a decent rule of thumb.)

So we can move work off the main thread and have a page that is responsive during that time, but to what end? If our user is sitting there looking at a spinner for 600ms, have we enriched their experience by having a responsive screen for the middle third?

No.

I’ve fudged these diagrams a little bit to make them the gorgeous specimens of graphic design that they are, but they’re not really to scale.

When responding to a user request, you’ll find that the network and DOM-manipulating part of any given task take much, much longer than the pure-JS data processing part.

I saw an article recently making the case that updating a Redux store was a good candidate for Web Workers because it’s not UI work (and non-UI work doesn’t belong on the main thread).

Chucking the data processing over to a worker thread sounds sensible, but the idea struck me as a little, umm, academic.

First, let’s split instances of ‘updating a store’ into two categories:

  1. Updating a store in response to a user interaction, then updating the UI in response to the data change
  2. Not that first one

If the first scenario, a user taps a button on the screen — perhaps to change the sort order of a list. The store updates, and this results in a re-rendering of the DOM (since that’s the point of a store).

Let me just delete one thing from the previous diagram:

In my experience, it is rare that the store-updating step goes beyond a few dozen milliseconds, and is generally followed by ten times that in DOM updating, layout, and paint. If I’ve got a site that’s taking longer than this, I’d be asking questions about why I have so much data in the browser and so much DOM, rather than on which thread I should do my processing.

So the question we’re faced with is the same one from above: the user tapped something on the screen, we’re going to work on that request for hopefully less than a second, why would we want to make the screen responsive during that time?

OK what about the second scenario, where a store update isn’t in response to a user interaction? Performing an auto-save, for example — there’s nothing more annoying than an app becoming unresponsive doing something you didn’t ask it to do.

Actually there’s heaps of things more annoying than that. Teens, for example.

Anyhoo, if you’re doing an auto-save and taking 100ms to process data client-side before sending it off to a server, then you should absolutely use a Web Worker.

In fact, any ‘background’ task that the user hasn’t asked for, or isn’t waiting for, is a good candidate for moving to a Web Worker.

The matter of value

Complexity is expensive, and implementing Web Workers ain’t cheap.

If you’re using a bundler — and you are — you’ll have a lot of reading to do, and probably npm packages to install. If you’ve got a create-react-app app, prepare to eject (and put aside two days twice a year to update 30 different packages when the next version of Babel/Redux/React/ESLint comes out).

Also, if you want to share anything fancier than plain data between a worker and the main thread you’ve got some more reading to do (comlink is your friend).

What I’m getting at is this: if the benefit is real, but minimal, then you’ve gotta ask if there’s something else you could spend a day or two on with a greater benefit to your users.

This thinking is true of everything, of course, but I’ve found that Web Workers have a particularly poor benefit-to-effort ratio.

Hey David, why you hate Web Workers so bad?

Good question.

This is a doweling jig:

I own a doweling jig. I love my doweling jig. If I need to drill a hole into the end of a piece of wood and ensure that it’s perfectly perpendicular to the surface, I use my doweling jig.

But I don’t use it to eat breakfast. For that I use a spoon.

Four years ago I was working on some fancy animations. They looked slick on a fast device, but janky on a slow one. So I wrote fireball-js, which executes a rudimentary performance benchmark on the user’s device and returns a score, allowing me to run my animations only on devices that would render them smoothly.

Where’s the best spot to run some CPU intensive code that the user didn’t request? On a different thread, of course. A Web Worker was the correct tool for the job.

Fast forward to 2019 and you’ll find me writing a routing algorithm for a mapping application. This requires parsing a big fat GeoJSON map into a collection of nodes and edges, to be used when a user asks for directions. The processing isn’t in response to a user request and the user isn’t waiting on it. And so, a Web Worker is the correct tool for the job.

It was only when doing this that it dawned on me: in the intervening quartet of years, I have seen exactly zero other instances where Web Workers would have improved the user experience.

Contrast this with a recent resurgence in Web Worker wonderment, and combine that contrast with the fact that I couldn’t think of anything else to write about, then concatenate that combined contrast with my contrarian character and you’ve got yourself a blog post telling you that maybe Web Workers are a teeny-tiny bit overhyped.

Thanks for reading

If you liked this post, share it with all of your programming buddies!

Follow us on Facebook | Twitter

Further reading

An Introduction to Web Workers

JavaScript Web Workers: A Beginner’s Guide

Using Web Workers to Real-time Processing

How to use Web Workers in Angular app

Using Web Workers with Angular CLI


Why ReactJS is better for Web Application Development?

Why ReactJS is better for Web Application Development?

Web Application Development is the point of contact for a business in today's digital era. It is important to choose the right platform for Web Application Development to build a high end Web

Web Application Development is essential for a business in today’s digital era. Finding the right platform for Web Application Development is important for building an effective Web Application that can enhance the overall customer engagement. Here’s what makes ReactJS a better option for building your next Web Application.