Create custom fetch hook for multiple Axios instances

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

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


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

查看所有标签

猜你喜欢:

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

UNIX网络编程 卷1:套接字联网API(第3版)

UNIX网络编程 卷1:套接字联网API(第3版)

[美]W. 理查德•史蒂文斯(W. Richard Stevens)、比尔• 芬纳(Bill Fenner)、安德鲁 M. 鲁道夫(Andrew M. Rudoff) / 匿名 / 人民邮电出版社 / 2014-6-1 / 129.00

《UNIX环境高级编程(第3版)》是被誉为UNIX编程“圣经”的Advanced Programming in the UNIX Environment一书的第3版。在本书第2版出版后的8年中,UNIX行业发生了巨大的变化,特别是影响UNIX编程接口的有关标准变化很大。本书在保持前一版风格的基础上,根据最新的标准对内容进行了修订和增补,反映了最新的技术发展。书中除了介绍UNIX文件和目录、标准I/......一起来看看 《UNIX网络编程 卷1:套接字联网API(第3版)》 这本书的介绍吧!

Markdown 在线编辑器
Markdown 在线编辑器

Markdown 在线编辑器

正则表达式在线测试
正则表达式在线测试

正则表达式在线测试