Skip to content

Instantly share code, notes, and snippets.

@jgthms
Forked from bartcis/useeffect_abort.js
Created July 22, 2022 08:16
Show Gist options
  • Save jgthms/ba6125025a37345e41bbb7bb58736e8c to your computer and use it in GitHub Desktop.
Save jgthms/ba6125025a37345e41bbb7bb58736e8c 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