Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save sfelix-martins/7a6484f2475f3fde67aa35b36a540e2a to your computer and use it in GitHub Desktop.
Save sfelix-martins/7a6484f2475f3fde67aa35b36a540e2a to your computer and use it in GitHub Desktop.
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