snippet
useFetch
import { useState, useEffect } from "react";
const useFetch = async (route) => {
const [Data, setData] = useState();
const [isErr, setIsErr] = useState(false);
useEffect(() => {
fetch(route)
.then((res) => {
const parsedData = res.json();
setData(parsedData);
})
.catch((err) => {
setIsErr(true);
setData(null);
console.error(err);
});
}, [route]);
return { Data, isErr };
};The hook situation
Now and again you have to implement some fetch request to get data from an API and writing the logic to get the data can be tedious, especiallywhen written multiple times throughout application. Luckily, the above hook abstracts data fetching into a handy little function that can be called from anywhere in your application.
How to use the useFetch hook
import useFetch from "./useFetch";
const App = () => {
const { Data, isErr } = useFetch("/api/hello");
return (
<>
{isErr && "Show a component when error occurs"}
{Data && "Display the component that show the data"}
</>
);
};The useFetch hook has two properties that it returns: 1) being the actual data, and 2) being and isErr boolean value. The isErr will be true if an error occurs while fetching your data, and false if the fetch is successful. Moreover, the data attribute will null if the fetch is not successful.
While this is a very handy hook, I recommend using something like react query from tanstack as this fetching library has built-in features that make data fetching seamless. Features such as caching, re-tries, mutations, data synchronization, and so much more!