Skip to content

Instantly share code, notes, and snippets.

@r007
Created December 28, 2019 15:52
Show Gist options
  • Save r007/032d17faa0934757f2853357c40dcdf4 to your computer and use it in GitHub Desktop.
Save r007/032d17faa0934757f2853357c40dcdf4 to your computer and use it in GitHub Desktop.
Fetch products hook
import { useState, useEffect } from 'react';
import { get } from '../utils/rest';
const useProducts = (url, dependencies = []) => {
// Set isLoading to true by default to indicate that data is loading
const [isLoading, setIsLoading] = useState(true);
const [fetchedProducts, setFetchedProducts] = useState([]);
const fetchProducts = (params = {}) =>
get(url, params)
.then(response => {
setIsLoading(false);
setFetchedProducts(response.data);
})
.catch(error => {
// eslint-disable-next-line no-console
console.log(`😱 fetchProduct() request failed: ${error}`);
setIsLoading(false);
// Stop execute javascript
return false;
});
// Check if component was unmounted to prevent memory leaks
const effectCallback = () => {
// New stuff here
let unmounted = false;
if (!unmounted) {
fetchProducts();
}
return () => {
// Bye bye!
unmounted = true;
};
};
useEffect(effectCallback, dependencies);
return [isLoading, fetchedProducts];
};
export default useProducts;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment