Skip to content

Instantly share code, notes, and snippets.

@muratdogan17
Last active October 28, 2023 09:23
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save muratdogan17/f5861e82e6db5545f651617823214172 to your computer and use it in GitHub Desktop.
Save muratdogan17/f5861e82e6db5545f651617823214172 to your computer and use it in GitHub Desktop.
Create custom fetch hook for multiple Axios instances - https://itnext.io/create-custom-fetch-hook-for-multiple-axios-instances-661a73701f73
import useFetch from "useFetch";
const { response, isLoading } = useFetch({
api: identityApi,
url: AUTH_MEMBER_TRANSACTIONS(requestOptions),
config: JSON.stringify({ requireAuthentication: true }),
});
import { useState, useEffect } from "react";
export default function useFetch({
api, method = "get", url, data = null, config = null,
}) {
const [response, setResponse] = useState(null);
const [error, setError] = useState("");
const [isLoading, setIsLoading] = useState(true);
useEffect(() => {
const fetchData = async () => {
try {
api[method](url, JSON.parse(config), JSON.parse(data))
.then((res) => {
setResponse(res.data);
})
.catch((err) => {
setError(err);
})
.finally(() => {
setIsLoading(false);
});
} catch (err) {
setError(err);
}
};
fetchData();
}, [api, method, url, data, config]);
return { response, error, isLoading };
}
@adover
Copy link

adover commented Sep 22, 2020

Nice snippet. You can use an IIFE in place of calling fetchData(); explicitly

const fetchData = async () => {
       // stuff here 
};

fetchData();

Becomes

(async () =>
    // stuff here 
)();

Also, it may also be safer to make api[method] to api[method.toLowerCase()] :)

@muratdogan17
Copy link
Author

@adover both of your comments are really helpful. I liked your point of view :) You made my day!

@emreuzelgok
Copy link

emreuzelgok commented Nov 11, 2021

You don't need an async function for that request by the way.
`
const fetchData = async () => {

try {
  const response = await api[method](url, config, data);  
  setResponse(response.data);
} catch (error) {
  setError(error)
}
setIsLoading(false);

};
`

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment