Skip to content

Instantly share code, notes, and snippets.

@aslamcodes
Created December 5, 2021 18:49
Show Gist options
  • Save aslamcodes/a28060bd264cfab7072d2afdea36d44e to your computer and use it in GitHub Desktop.
Save aslamcodes/a28060bd264cfab7072d2afdea36d44e to your computer and use it in GitHub Desktop.
import { useEffect, useState, useCallback } from "react";
import axios, { AxiosRequestConfig } from "axios";
export default function useAxiosWithCallback() {
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState(null);
const fetchData = useCallback(
async (config: AxiosRequestConfig, callback = () => {}) => {
const axiosConfig = {
method: "get",
headers: {
"Content-Type": "application/json",
...config.headers,
},
...config,
} as AxiosRequestConfig;
try {
setIsLoading(true);
const response = await axios(axiosConfig);
if (!response.status) {
throw new Error("Problem connecting to server");
}
callback(response.data);
} catch (error) {
setError(error);
} finally {
setIsLoading(false);
}
},
[]
);
useEffect(() => {
const fetchData = async () => {};
fetchData();
}, []);
return { isLoading, error, fetchData };
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment