From 38654f81cfacf8803bbf0a55b5e01b2b372b4cc0 Mon Sep 17 00:00:00 2001 From: Mark <34482614+MarkLabe@users.noreply.github.com> Date: Tue, 26 Nov 2024 20:45:42 +0200 Subject: [PATCH] 2147 - added logic to update cache for multiple baskets on basket mutations Signed-off-by: Mark <34482614+MarkLabe@users.noreply.github.com> --- .../src/hooks/ShopperBaskets/cache.ts | 33 +++++++++++++------ 1 file changed, 23 insertions(+), 10 deletions(-) diff --git a/packages/commerce-sdk-react/src/hooks/ShopperBaskets/cache.ts b/packages/commerce-sdk-react/src/hooks/ShopperBaskets/cache.ts index a2922fc78c..0593b20bee 100644 --- a/packages/commerce-sdk-react/src/hooks/ShopperBaskets/cache.ts +++ b/packages/commerce-sdk-react/src/hooks/ShopperBaskets/cache.ts @@ -43,29 +43,42 @@ const invalidateCustomerBasketsQuery = ( } } -const updateCustomerBasketsQuery = ( - customerId: string, - parameters: BasketParameters, - response: Basket -): CacheUpdateUpdate => { +const updateCustomerBasketsQuery = (customerId: string, parameters: BasketParameters, response: Basket): CacheUpdateUpdate => { return { queryKey: getCustomerBaskets.queryKey({...parameters, customerId}), updater: (oldData: CustomerBasketsResult | undefined) => { + // custom code to enable multiple baskets query upadte + let isBasketNew = true + let basketsTotal = 1 if (!oldData?.baskets?.length) { return { baskets: [response], - total: 1 + total: basketsTotal + } + } + + basketsTotal = oldData.total + const updatedBaskets = oldData.baskets.map((basket) => { + if (basket.basketId === parameters.basketId) { + isBasketNew = false + return response + } else { + return basket } + }) + + if (isBasketNew) { + updatedBaskets[basketsTotal] = response + basketsTotal += 1 } - const updatedBaskets = oldData.baskets.map((basket) => - basket.basketId === parameters.basketId ? response : basket - ) + return { ...oldData, // Shopper Customers and Shopper Baskets have different definitions for the `Basket` // type. (99% similar, but that's not good enough for TypeScript.) // TODO: Remove this type assertion when the RAML specs match. - baskets: updatedBaskets as CustomerBasketsResult['baskets'] + baskets: updatedBaskets as CustomerBasketsResult['baskets'], + total: basketsTotal } } }