// version : async await
import React from 'react';
const useFetch = (url, options) => {
const [response, setResponse] = React.useState(null);
const [error, setError] = React.useState(null);
const [isLoading, setIsLoading] = React.useState(true);
React.useEffect(() => {
(async () => {
try {
const res = await fetch(url, options);
const json = await res.json();
setResponse(json);
setIsLoading(false)
} catch (error) {
setError(error);
}
})()
}, []);
return { response, error, isLoading };
};
export default useFetch
// version : Promise
import React from 'react';
const useFetch = (url, options) => {
const [response, setResponse] = React.useState(null);
const [error, setError] = React.useState(null);
const [isLoading, setIsLoading] = React.useState(true);
React.useEffect(() => {
(async () => {
fetch(url, options)
.then(res => res.json())
.then(json => {
setResponse(json)
setIsLoading(false)
})
.catch(error => {
setError(error);
})
})()
}, []);
return { response, error, isLoading };
};
export default useFetch