Implements fetch()
in a declarative manner.
url
and options
.useState()
hook to initialize the response
, error
and abort
state variables.useEffect()
hook to asynchronously call fetch()
and update the state variables accordingly.AbortController
to allow aborting the request. Use it to cancel the request when the component unmounts.response
, error
and abort
state variables.const useFetch = (url, options) => {
const [response, setResponse] = React.useState(null);
const [error, setError] = React.useState(null);
const [abort, setAbort] = React.useState(() => {});
React.useEffect(() => {
const fetchData = async () => {
try {
const abortController = new AbortController();
const signal = abortController.signal;
setAbort(abortController.abort);
const res = await fetch(url, {...options, signal});
const json = await res.json();
setResponse(json);
} catch (error) {
setError(error);
}
};
fetchData();
return () => {
abort();
}
}, []);
return { response, error, abort };
};
const ImageFetch = props => {
const res = useFetch('https://dog.ceo/api/breeds/image/random', {});
if (!res.response) {
return <div>Loading...</div>;
}
const imageUrl = res.response.message;
return (
<div>
<img src={imageUrl} alt="avatar" width={400} height="auto" />
</div>
);
};
ReactDOM.render(<ImageFetch />, document.getElementById('root'));
React, Hooks
Implements setTimeout()
in a declarative manner.
React, Hooks
Implements setInterval()
in a declarative manner.
React, Hooks
Tracks the browser's location search param.