32

Create custom fetch hook for multiple Axios instances

 3 years ago
source link: https://medium.com/@muratdogan/create-custom-fetch-hook-for-multiple-axios-instances-661a73701f73
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.

It might be fun when you first start to convert your existing codebase to hooks or start to write your components from scratch using React Hooks.

After a few repetitive components, you will get rid of the repeated code blocks, especially while making some network requests. There are so many similar things in each request code block. Setting loading indicator, handling errors, setting response data etc.

It sounds unnecessary until you feel that pain. I got this feeling at the very beginning of my project and needed to figure out a scalable and maintainable solution.

Custom hooks!

Custom hooks allow us to build new hooks using React’s hooks. As I mentioned before, If you have some repeated blocks, processes you can create middleware-ish hooks which handle this work for each time. It’s kind of utility function, in fact. So, let's build our own custom hook for Axios instances:

VJz2QfN.jpg!web

Credit: Unsplash

First thing first, let's define our instances:

export const contentApi = axios.create({
baseURL: contentApiUrl,
});

export const programApi = axios.create({
baseURL: programApiUrl,
});

I need to create this kind of instances because I need to group my requests and each of them needs different options, interceptors, base URLs etc. Because I have more than 8 different APIs.

Second, create a file called useFetch.js:

import { useState, useEffect } from "react";

export default function useFetch({ api, method, url, data = null, config = null }) {
   const [response, setResponse] = useState(null);
   const [error, setError] = useState("");
   const [isLoading, setIsLoading] = useState(false);

   useEffect(() => {
      const fetchData = async () => {
         setIsLoading(true);
         try {
            api[method](url, data, config).then((res) => setResponse(res.data));
            setIsLoading(false);
         } catch (err) {
            setError(err);
         }
      };

      fetchData();
   }, [api, method, url, data, config]);

   return [response, error, isLoading];
}

Here is the easiest way to get rid of using setLoading in every network request:

import useFetch from "../hooks/useFetch";const [response, isLoading] = useFetch({
api: programApi,
method: "get",
url: "/SportsProgram/active_sport_type",
});

You can now listen to your response in useEffect and do whatever you want:

useEffect(() => {
   if (response !== null) {
      // do more stuff if you wish
   }
}, [response]);

It is always better to keep it easy to read and understand. If you have any comments to improve this hook, please let me know because this is my first custom hook shot!

Enjoy


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK