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


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

查看所有标签

猜你喜欢:

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

Effective Objective-C 2.0

Effective Objective-C 2.0

Matt Galloway / 爱飞翔 / 机械工业出版社 / 2014-1 / 69.00元

《effective objective-c 2.0:编写高质量ios与os x代码的52个有效方法》是世界级c++开发大师scott meyers亲自担当顾问编辑的“effective software development series”系列丛书中的新作,amazon全五星评价。从语法、接口与api设计、内存管理、框架等7大方面总结和探讨了objective-c编程中52个鲜为人知和容易被忽......一起来看看 《Effective Objective-C 2.0》 这本书的介绍吧!

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

在线图片转Base64编码工具

MD5 加密
MD5 加密

MD5 加密工具

XML 在线格式化
XML 在线格式化

在线 XML 格式化压缩工具