schon/storefront/app/composables/wishlist/useWishlistSync.ts
Alexandr SaVBaD Waltz 9bf600845a feat(storefront): enhance cart and wishlist handling with cookie-based products support
Introduced `useExactProducts` composable to fetch precise product details for guest cart and wishlist items. Improved cookie-based cart and wishlist fallback handling for unauthenticated users. Updated related components and composables for better synchronization and type safety.

- Added `useExactProducts` composable leveraging the `GET_EXACT_PRODUCTS` query.
- Enhanced `wishlist.vue` and `cart.vue` for reactive updates on guest state changes.
- Improved product synchronization logic in `useOrderSync` and `useWishlistSync`.
- Updated translations and fixed minor typos in localization files.

Improves user experience by ensuring consistent product details, even for guests. No breaking changes.
2026-03-02 23:06:13 +03:00

59 lines
1.4 KiB
TypeScript

import { useWishlistOverwrite } from '@composables/wishlist/useWishlistOverwrite';
export function useWishlistSync() {
const wishlistStore = useWishlistStore();
const userStore = useUserStore();
const { $appHelpers } = useNuxtApp();
const { overwriteWishlist } = useWishlistOverwrite();
const isAuthenticated = computed(() => userStore.isAuthenticated);
const wishlistUuid = computed(() => wishlistStore.wishlist?.uuid);
const cookieWishlist = useCookie($appHelpers.COOKIES_WISHLIST_KEY, {
default: () => [],
path: '/',
});
async function syncWishlist() {
if (!isAuthenticated.value || !wishlistUuid.value) {
return;
}
const cookieProducts = cookieWishlist.value || [];
if (cookieProducts.length === 0) {
return;
}
const apiProductUuids = wishlistStore.wishlist?.products?.edges.map((e) => e.node.uuid) || [];
const productsToAdd = cookieProducts.filter((product) => !apiProductUuids.includes(product));
if (productsToAdd.length === 0) {
cookieWishlist.value = [];
return;
}
try {
await overwriteWishlist({
type: 'bulk',
bulkAction: 'add',
isBulkSync: true,
products: productsToAdd.map(uuid => ({ uuid }))
});
if (bulkResult?.data?.bulkWishlistAction?.wishlist) {
wishlistStore.setWishlist(bulkResult.data.bulkWishlistAction.wishlist);
cookieWishlist.value = [];
}
} catch (err) {
console.error('useWishlistSync error:', err);
}
}
return {
syncWishlist,
};
}