Declarative Data Fetching with React Async
source link: https://blog.bitsrc.io/declarative-data-fetching-with-react-async-d4dfc63b0597
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Declarative Data Fetching with React Async
Using React Async to Handle Asynchronous UI States in React Applications
With JavaScript, we typically use async/await for asynchronous operations like data fetching. The same remains even if we use UI libraries like React. But, what if you get a React component and a Hook to fetch data instead?
React Async exactly does that by providing a component-driven approach to fetch data from an API. In this article, I will discuss its core features to give you a better understanding.
Introduction to React-Async
Source: https://www.npmjs.com/package/react-asyncReact Async is a promise-based library that offers a declarative API to make API calls. It provides a React component and a Hook for declarative promise resolution and data fetching.
React Async is compatible with almost all the data fetching libraries and APIs, including Fetch API, Axios, and GraphQL. Also, it works well with React Native too.
Installing React Async
Installing React Async is pretty straightforward. You can treat it like any other JavaScript library and install it using NPM or Yarn.
//NPM
npm install — save react-async//Yarn
yarn add react-async
It has more than 33K weekly downloads and 2K GitHub stars.
Note: Please keep in mind to install React as a peer dependency for this package. You’ll need [email protected] or later if you wish to use the
useAsync
hook.
Basics of React Async
React Async is a simple library. To get things started, you need to get familiar with its three main APIs:
1. <Async>
component.
2. useAsync
hook.
3. createInstance
factory function.
So, let’s see what those APIs are and their usage in detail.
1. As a Component — <Async>
Async component is the classic interface of React Async, and we can use it to make React components more declarative. Here, we can directly use the <Async>
component in JSX to apply the render props pattern.
Following is a simple example of using <Async>
component to fetch data.
In the above example fetch API
is used to perform the API call inside the loadUsers
function. It returns a Promise. And we can access the props, from the Promise parameters it returns.
The props are as follows:
data
: Requested data from the server.error
: For instances where an error occurs.isLoading
: For scenarios where the server response is still in progress.
With React Async, we don’t need to exploit classes or lifecycle methods to fetch data and no need to specify how to handle the data.
2. As a Hook — useAsync
The
useAsync
Hook allows you to use React Async basic functionalities directly in functional components.
If you are fond of using React Hooks, you can use the useAsync
Hook instead of <Async>
component. The below example shows how we can use the useAsync
Hook to fetch data.
As you can see, I have passed the data fetching method loadUsers
to useAsync
Hook. And you can access the result, errors, or status using the props.
The library also offers another Hook called useFetch dedicated to use with Fetch API.
3. As a Factory Function — createInstance()
React Async offers a factory function called createInstance()
. It allows you to design your component instances with options like default onResolve
and onReject
callbacks.
The below example, shows how we can create a custom instance of the Async
component using createInstance().
By default, createInstance()
accepts two input parameters, defaultOptions
and the displayName
. In the above example, I have passed;
loadUsers
function — ThedefaultOption
.AsyncUser
— The instance’s display name.
Helper Components in React Async
Apart from the Async component, React Async provides several helper components to make JSX more declarative and clutter-free.
These Helper components can take a React element or a function as children and enable or disable rendering based on the current state. We can pass the current state to useAsync
, or <Async>
by using the Context.
Here is an example of how to use useAsync
with the helpers. It is pretty much similar to using props.
In the above example, I have used three helper components:
<IfPending>
— Renders only while the Promise is pending (loading / unsettled).<IfRejected>
— Renders only when the Promise is rejected.<IfFulfilled>
— Renders only when the Promise is fulfilled (resolved to a value, could beundefined
).
Helper components can increase the readability of your render functions by eliminating the need to write conditional returns.
Additional Features of React Async
React Async has a special DevTools package that facilitates debugging and development of asynchronous application states.
You can install it using NPM or Yarn with the following commands:
//NPM
npm install --save react-async-devtools//Yarn
yarn add react-async-devtools
After installation, you need to import it and render the <DevTools/>
component in your app root like this.
Apart from that, React Async offers plenty of configuration options to handle special scenarios.
These configurations can be sent as props to <Async {…options}>
and custom instances, or as an object to useAsync(options)
.
Some of the most used configurations options are:
promise
- An already started Promise instance.promiseFn
- A function that returns a Promise that is automatically invoked.initialValue
- Provide initial data or errors for server-side rendering.onResolve
- A callback invoked when Promise resolves.onReject
- A callback invoked when Promise rejects.onCancel
- A callback invoked when a Promise is canceled.
Build with independent components for speed and scale
Instead of building monolithic apps, build independent components first and compose them into features and applications. It makes development faster and helps teams build more consistent and scalable applications.
Bit offers a great developer experience for building independent components and composing applications. Many teams start by building their Design Systems or Micro Frontends, through independent components.
Give it a try →
Final Thoughts
In this article, I discussed how to use React Async library for declarative data fetching. It aims to resolve data as close as possible to where they will be consumed, just using declarative syntax and native promises.
React Async performs effectively even in complex applications with extensive nested data dependencies. It promotes loading data at the component level on-demand in parallel rather than loading bulks at a higher route or page levels.
Further, it would be ideal for large applications with a dynamic routing model or no routes since it’s completely independent of your routes.
So, I invite you all to use declarative data fetching with React Async in your next React project and share your thoughts in the comments section.
Thank you for reading..!!
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK