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


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

查看所有标签

猜你喜欢:

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

Redis实战

Redis实战

Josiah L. Carlson / 黄健宏 / 人民邮电出版社 / 2015-10

【内容简介】 本书深入浅出地介绍了Redis的5种数据类型,并通过多个实用示例展示了Redis的用法。除此之外,书中还讲述了Redis的优化方法以及扩展方法,是一本对于学习和使用 Redis 来说不可多得的参考书籍。 本书一共由三个部分组成。第一部分对Redis进行了介 绍,说明了Redis的基本使用方法、它拥有的5种数据结构以及操作这5种数据结构的命令,并讲解了如何使用Redis去构......一起来看看 《Redis实战》 这本书的介绍吧!

RGB转16进制工具
RGB转16进制工具

RGB HEX 互转工具

图片转BASE64编码
图片转BASE64编码

在线图片转Base64编码工具

SHA 加密
SHA 加密

SHA 加密工具