Skip to content

Commit 25d814c

Browse files
committed
Custom hook to dispatch action to fetch products
1 parent 72b327a commit 25d814c

File tree

2 files changed

+20
-1
lines changed

2 files changed

+20
-1
lines changed

src/hooks/useGetProducts.js

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
import { useDispatch } from 'react-redux';
2+
import { getProducts } from '../features/product/productSlice.js';
3+
import { useProducts } from './useStoreItems.js';
4+
5+
const useGetProducts = () => {
6+
7+
const dispatch = useDispatch();
8+
const productData = useProducts();
9+
10+
if (productData && productData.length > 0) return;
11+
12+
13+
dispatch(getProducts());
14+
};
15+
16+
export default useGetProducts;

src/hooks/useStoreItems.js

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,8 @@
11
import { useSelector } from 'react-redux';
22

3+
// Custom hook to use product state from store.
4+
const useProducts = () => useSelector(state => state.product.value);
5+
36
// Custom hook to use cart state from store.
47
const useCartItems = () => useSelector(state => state.cart.value);
58

@@ -20,4 +23,4 @@ const useIsItemInWishlist = () => (itemName) => {
2023
return wishlistItems.some(item => item.name === itemName);
2124
};
2225

23-
export { useCartItems, useWishlistItems, useIsItemInCart, useIsItemInWishlist };
26+
export { useProducts, useCartItems, useWishlistItems, useIsItemInCart, useIsItemInWishlist };

0 commit comments

Comments
 (0)