Skip to content

Instantly share code, notes, and snippets.

@bartcis
Last active July 22, 2022 08:16
Show Gist options
  • Save bartcis/1db87692f2e90de96821305d361a7c91 to your computer and use it in GitHub Desktop.
Save bartcis/1db87692f2e90de96821305d361a7c91 to your computer and use it in GitHub Desktop.
Abort signal on initial fetch of API
export const Articles = () => {
const [state, setState] = useState([]);
useEffect(() => {
const abortController = new AbortController();
const {signal} = abortController;
const apiCall = async path => {
try {
const request = await fetch(path, {
signal: signal,
method: 'GET',
});
const response = await request.json();
setState([response]);
} catch (e) {
if (!signal?.aborted) {
console.error(e);
}
}
};
apiCall('https://jsonplaceholder.typicode.com/posts/1');
return () => {
abortController.abort();
};
}, [setState]);
return (
<>
{state.map(article=> (
<article key={article?.id} className='article'>
<h1>{article?.title}</h1>
<p>{article?.body}</p>
</article>
))}
</>
);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment