Introduction
In this lab, we will learn about the useFetch hook in React. This hook allows us to implement the fetch() method in a declarative manner, making it easier to fetch data from APIs and update the component state. We will create a custom hook that takes a URL and options, and asynchronously calls fetch() to update the response, error, and abort state variables.
React useFetch Hook
index.htmlandscript.jshave already been provided in the VM. In general, you only need to add code toscript.jsandstyle.css.
Here is the code:
const useFetch = (url, options) => {
const [response, setResponse] = React.useState(null);
const [error, setError] = React.useState(null);
const [abort, setAbort] = React.useState(() => {});
React.useEffect(() => {
const abortController = new AbortController();
const signal = abortController.signal;
const fetchData = async () => {
try {
const res = await fetch(url, { ...options, signal });
const json = await res.json();
setResponse(json);
} catch (error) {
setError(error);
}
};
fetchData();
return () => {
abort();
};
}, []);
return { response, error, abort };
};
const ImageFetch = (props) => {
const res = useFetch("https://dog.ceo/api/breeds/image/random", {});
if (!res.response) {
return <div>Loading...</div>;
}
const imageUrl = res.response.message;
return (
<div>
<img src={imageUrl} alt="avatar" width={400} height="auto" />
</div>
);
};
ReactDOM.createRoot(document.getElementById("root")).render(<ImageFetch />);
Explanation:
- The purpose of the code is to implement a
fetch()call in a declarative manner using React hooks. - The
useFetchhook takes two parameters: aurlandoptionsobject. - The hook initializes three state variables using the
useState()hook:response,error, andabort. - The
useEffect()hook is used to asynchronously callfetch()and update the state variables accordingly. - An
AbortControlleris used to allow aborting the request, and it's used to cancel the request when the component unmounts. - The hook returns an object containing the
response,error, andabortstate variables. - The
ImageFetchcomponent uses theuseFetchhook to fetch a random dog image and display it in an<img>element.
Please click on 'Go Live' in the bottom right corner to run the web service on port 8080. Then, you can refresh the Web 8080 Tab to preview the web page.
Summary
Congratulations! You have completed the React useFetch Hook lab. You can practice more labs in LabEx to improve your skills.