I have two components rendering different UI based on user type. Both components have nearly 50% similar logic of fetching data from api, connecting to store.
I tried, reusing the login by creating custom hook.
const { products, loading} = useFetchProducts(userId);
and now I can define a useFetchProducts reducer
const useFetchProducts= (userId) => {
const [ loading, setLoading ] = useState(false);
const [ products, setProducts ] = useState(null);
useEffect(() => {
setLoading(true);
fetchUserProducts(userId).then((res) => {
setLoading(false);
setProducts(res.data);
});
}, [])
}
How do I return products and loading state to my component from this reducer to hide or show a loader as well as to show list of products,