Last active
July 22, 2022 08:16
-
-
Save bartcis/1db87692f2e90de96821305d361a7c91 to your computer and use it in GitHub Desktop.
Abort signal on initial fetch of API
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
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