-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #28 from MakairaIO/feat/add-is-product-part-of-wis…
…hlist feat(useShopWishlist): add isProductInWishlist to check if product is…
- Loading branch information
Showing
1 changed file
with
21 additions
and
2 deletions.
There are no files selected for viewing
23 changes: 21 additions & 2 deletions
23
packages/storefront-react/src/hooks/use-shop-wishlist.hook.ts
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,15 +1,34 @@ | ||
import { useContext } from 'react' | ||
import { MakairaResponse } from '@makaira/storefront-types' | ||
import { useCallback, useContext } from 'react' | ||
import { ShopContext, ShopContextData } from '../context' | ||
|
||
export type UseShopWishlistData = { | ||
/** | ||
* The current wishlist with the products | ||
*/ | ||
wishlist: ShopContextData['wishlist'] | ||
/** | ||
* | ||
*/ | ||
isProductInWishlist: (id: string) => MakairaResponse<boolean, Error> | ||
} | ||
|
||
export function useShopWishlist(): UseShopWishlistData { | ||
const { wishlist } = useContext(ShopContext) | ||
|
||
return { wishlist } | ||
const isProductInWishlist = useCallback( | ||
(id: string): MakairaResponse<boolean, Error> => { | ||
if (wishlist?.items) { | ||
return { | ||
data: wishlist.items.some(({ product }) => product.id === id), | ||
error: undefined, | ||
} | ||
} | ||
|
||
return { data: undefined, error: new Error('Wishlist is not loaded') } | ||
}, | ||
[wishlist] | ||
) | ||
|
||
return { wishlist, isProductInWishlist } | ||
} |