React useFetch Hook

ReactReactBeginner
Practice Now

This tutorial is from open-source community. Access the source code

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.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL react(("`React`")) -.-> react/FundamentalsGroup(["`Fundamentals`"]) react(("`React`")) -.-> react/AdvancedConceptsGroup(["`Advanced Concepts`"]) react(("`React`")) -.-> react/StateManagementGroup(["`State Management`"]) react/FundamentalsGroup -.-> react/jsx("`JSX`") react/AdvancedConceptsGroup -.-> react/hooks("`React Hooks`") react/StateManagementGroup -.-> react/use_state_reducer("`Using useState and useReducer`") subgraph Lab Skills react/jsx -.-> lab-38384{{"`React useFetch Hook`"}} react/hooks -.-> lab-38384{{"`React useFetch Hook`"}} react/use_state_reducer -.-> lab-38384{{"`React useFetch Hook`"}} end

React useFetch Hook

index.html and script.js have already been provided in the VM. In general, you only need to add code to script.js and style.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;
    setAbort(abortController.abort);

    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 useFetch hook takes two parameters: a url and options object.
  • The hook initializes three state variables using the useState() hook: response, error, and abort.
  • The useEffect() hook is used to asynchronously call fetch() and update the state variables accordingly.
  • An AbortController is 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, and abort state variables.
  • The ImageFetch component uses the useFetch hook 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.

Other React Tutorials you may like