Skip to content

Instantly share code, notes, and snippets.

@suhas86
Created September 15, 2020 10:23
Show Gist options
  • Save suhas86/b162e36220c6cdcb6e2df73502a5b5ce to your computer and use it in GitHub Desktop.
Save suhas86/b162e36220c6cdcb6e2df73502a5b5ce to your computer and use it in GitHub Desktop.
import React from "react";
import axios from "axios";
const API = "https://fakestoreapi.com";
export default function useAxios(path, method, body) {
const [response, setResponse] = React.useState(null);
const [loading, setLoading] = React.useState(true);
React.useEffect(() => {
const abortController = new AbortController();
const signal = abortController.signal;
axios(`${API}${path}`, {
method,
...(body ? { body } : {}),
headers: {
Accept: "application/json",
"Content-Type": "application/json",
},
})
.then((response) => {
if (!signal.aborted) {
setResponse(response.data);
setLoading(false);
}
})
.catch((error) => console.warn("Something gone wrong", error));
return () => abortController.abort();
}, [path, method, body]);
return { response, loading };
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment