Created
December 28, 2019 15:52
-
-
Save r007/032d17faa0934757f2853357c40dcdf4 to your computer and use it in GitHub Desktop.
Fetch products hook
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
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