Create custom fetch hook for multiple Axios instances

栏目: IT技术 · 发布时间: 4年前

内容简介: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 n

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:

Create custom fetch hook for multiple Axios instances

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


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

金字塔原理

金字塔原理

[美] 巴巴拉·明托 / 王德忠、张珣 / 民主与建设出版社 / 2002-12 / 39.80元

《金字塔原理》是一本讲解写作逻辑与思维逻辑的读物,全书分为四个部分。 第一篇主要对金字塔原理的概念进行了解释,介绍了如何利用这一原理构建基本的金字塔结构。目的是使读者理解和运用简单文书的写作技巧。 第二篇介绍了如何深入细致地把握思维的环节,以保证使用的语句能够真实地反映希望表达的思想要点。书中列举了许多实例,突出了强迫自己进行“冷静思维”对明确表达思想的重要性。 第三篇主要针对的......一起来看看 《金字塔原理》 这本书的介绍吧!

SHA 加密
SHA 加密

SHA 加密工具

html转js在线工具
html转js在线工具

html转js在线工具

RGB CMYK 转换工具
RGB CMYK 转换工具

RGB CMYK 互转工具