Created
May 10, 2019 20:49
-
-
Save sfelix-martins/7a6484f2475f3fde67aa35b36a540e2a to your computer and use it in GitHub Desktop.
This file contains hidden or 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
useEffect(() => { | |
if (products.length > 0) { | |
return; | |
} | |
const [request, cancel] = getProductsRequest(); | |
let isSubscribed = true; | |
async function fetchProducts() { | |
try { | |
setLoading(true); | |
const { | |
data: { data }, | |
} = await request; | |
if (isSubscribed) { | |
setProducts(data); | |
setLoadingError(false); | |
setLoading(false); | |
} | |
} catch (err) { | |
if (isSubscribed) { | |
setLoadingError(true); | |
setLoading(false); | |
} | |
} | |
} | |
fetchProducts(); | |
return () => { | |
cancel(); | |
isSubscribed = false; | |
}; | |
}, [products.length]); | |
////////////// | |
export const getProductsRequest = () => { | |
let cancel; | |
const { CancelToken } = axios; | |
const request = api.get('v1/products', { | |
cancelToken: new CancelToken((c) => { | |
cancel = c; | |
}), | |
}); | |
return [request, cancel]; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment