Simpler Async State Management in React Apps with Hyperfetch
Reuben09
Posted on April 22, 2023
Introduction
Reactjs, a Javascript library that has no specific pattern for data fetching, the most basic approach it uses is the useEffect
hook for data fetching and the useState
hook to handle the state of the component, including any loading errors or gathered information.
But then, when it comes to managing caching, getting rid of duplicate requests for the same information, changing state data in the background, and improving performance, it can be a difficult task. Believe me, it takes a lot of time and energy to take care of all these elements in an application if you do it on your own.
Rather than attempting to manage all of these tasks yourself, you can make use of a library like Hyperfetch
, which will make managing these tasks much easier.
What is Hyperfetch
Hyperfetch is a library designed to make it easier for developers to manage and manipulate data.
Are you familiar with Axios and React Query? Hyperfetch is a combination of both of these, with the bonus of more persistence options. It is suitable for any Javascript or Typescript environment, such as Nodejs, Reactjs, Angular, Svelte, Vue, and more.
Getting Started with Hyperfetch
In this portion of this article, I'm going to demonstrate how to integrate Hyperfetch into a Reactjs application. Before we start, let us configure our development environment.
Setting up Our Development Environment
In this guide, we are going to build a new React project with the help of Vite.
Launch any terminal you would like to use and type in the following command:
npm create vite@latest
After that, Vite will request the name of your project, for this lesson I will name mine react-hyperfetch-tutorial
:
Next, Vite will want to know if you are using React or another library, choose React.
Once the command has finished running, navigate into the app and run the following in the terminal:
npm install
npm run dev
Installing Hyperfetch and Setup Instructions
Install Hyperfetch in your React app by running this command:
npm install --save @hyper-fetch/core @hyper-fetch/react
Now, this is where it gets interesting, to use Hyperfetch in our application we need to initialize two instances:
Client Instance.
Request Instance.
Initialize the client instance: The client instance will set up our connection to the server, all you have to do on your path is to determine the base URL of the server you want to work with.
Now let's write some code:
I’ll be working with a public API JSON placeholder, and the base URL of this API is
https://jsonplaceholder.typicode.com
.Now inside the
src
directory make a new folder, and call it server. Then within the server folder, make a newclient.js
file and add the snippet below:
// client.js
import { Client } from "@hyper-fetch/core";
export const client = new Client({ url: "https://jsonplaceholder.typicode.com" });
Initialize the request instance: Hyperfetch allows us to create multiple reusable requests, and in addition to this, we can set up how these requests will work. While the majority of the settings are not compulsory, the only two that are required are the method
and endpoint
configurations.
The method configuration is where we put in whatever HTTP
request method we want to use, for example, the GET
or POST
HTTP
methods.
The endpoint configuration is where we put in whatever path we want to request.
Enough of the talks, let’s get to work, create a new folder in your server directory and call it auth
, and then make a new file titled auth.js
within that folder and insert the provided code snippet:
// auth.js
import { client } from "../client.js";
export const getPosts = client.createRequest()({
method: "GET",
endpoint: "/posts"
});
Now let's see how to fetch data.
Fetching data with the UseFetch hook
The useFetch
hook is created to retrieve data from servers, and the many helper hooks it has will help you handle various events in the request flow and life cycle.
- Import the
useFetch
hook into your App.js file
// App.js
import { useFetch } from "@hyper-fetch/react";
- Import the
getPosts
request and pass it as an argument to theuseFetch
hook:
import { useFetch } from "@hyper-fetch/react";
import { getPosts } from "./server/auth/auth";
const App = () => {
const { data, error, loading, onSuccess, onError, onFinished } =
useFetch(getPosts);
onSuccess(({ response }) => {
console.log(response); // [ User, User, User ]
});
onError(({ response }) => {
console.log(response); // { message: string }
});
onFinished(({ response }) => {
const [payload, error, status] = response;
console.log(payload); // [ User, User, User ] | null
console.log(error); // { message: string } | null
console.log(status); // 200 / 400 / 404 / 500
});
return (
<div>
<h1> Hi</h1>
</div>
);
};
export default App;
From the above snippet the useFetch
hook returns an object that contains the following properties: data
: The response returned by the server.
error
: Contains information about any errors that occurred during the request.
loading
: A boolean value that indicates whether the request is still in progress or has been completed.
onSucess
: A callback function that is called when the request succeeds.
onError
: A callback function that is called when the request fails.
onFinished
: A callback function that is called when the request completes whether it succeeded or failed.
- Inside the JSX, return a list of post titles by mapping through data
import { useFetch } from "@hyper-fetch/react";
import { getPosts } from "./server/auth/auth";
const App = () => {
const { data, error, loading, onSuccess, onError, onFinished } = useFetch(
getPosts
);
onSuccess(({ response }) => {
console.log(response); // [ User, User, User ]
});
onError(({ response }) => {
console.log(response); // { message: string }
});
onFinished(({ response }) => {
const [payload, error, status] = response;
console.log(payload); // [ User, User, User ] | null
console.log(error); // { message: string } | null
console.log(status); // 200 / 400 / 404 / 500 ...
});
if(loading){
return <div>loading...</div>
} else {
return(
<div>
<h1>POST TITLES</h1>
{data?.map((post) => {
return <li>{post.title}</li>;
})}
</div>
)
}
}
export default App;
Conclusion
In this article, I've introduced Hyperfetch while also stating the problems it solves. I also demonstrated how to install Hyperfetch into a Reactjs program and the steps needed to get it working. Lastly, I described how to make use of Hyperfetch to fetch data from any API endpoint.
Reference
Hyperfetch docs- https://hyperfetch.bettertyped.com/
Json placeholder- https://jsonplaceholder.typicode.com/
Posted on April 22, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.