MENU
Out of order Responses
We can handle out-of-order responses with a local variable inside the effect.
// WARNING! async function must not be passed directly!
// useEffect(async () => {
// const response = await fetch(`https://www.reddit.com/r/${subreddit}.json`);
// const json = await response.json();
// …
// }, []);
React.useEffect(() => {
let ignore = false;
async function fetchProduct() {
const response = await fetch('http://myapi/product/' + productId);
const json = await response.json();
if (!ignore) setProduct(json);
}
fetchProduct();
return () => { ignore = true };}, [productId]);