Last active
June 3, 2024 16:14
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import useFetch from "useFetch"; | |
const { response, isLoading } = useFetch({ | |
api: identityApi, | |
url: AUTH_MEMBER_TRANSACTIONS(requestOptions), | |
config: JSON.stringify({ requireAuthentication: true }), | |
}); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 }; | |
} |
Hİ @adover both of your comments are really helpful. I liked your point of view :) You made my day!
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
Nice snippet. You can use an IIFE in place of calling
fetchData();
explicitlyBecomes
Also, it may also be safer to make
api[method]
toapi[method.toLowerCase()]
:)