Created
September 15, 2020 10:23
-
-
Save suhas86/b162e36220c6cdcb6e2df73502a5b5ce to your computer and use it in GitHub Desktop.
This file contains 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 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