From 8a244d9feeaebe181079a310ed2155d1471c279b Mon Sep 17 00:00:00 2001 From: Thomas Roberts Date: Tue, 11 Oct 2022 12:20:41 +0100 Subject: [PATCH] Remove cart notices before showing new ones --- .../filled-cart-block/frontend.tsx | 21 ++++++++++++++++--- 1 file changed, 18 insertions(+), 3 deletions(-) diff --git a/assets/js/blocks/cart/inner-blocks/filled-cart-block/frontend.tsx b/assets/js/blocks/cart/inner-blocks/filled-cart-block/frontend.tsx index 03ef72c9e34..d16947b48e3 100644 --- a/assets/js/blocks/cart/inner-blocks/filled-cart-block/frontend.tsx +++ b/assets/js/blocks/cart/inner-blocks/filled-cart-block/frontend.tsx @@ -6,7 +6,7 @@ import { SidebarLayout } from '@woocommerce/base-components/sidebar-layout'; import { useStoreCart } from '@woocommerce/base-context/hooks'; import { useEffect } from '@wordpress/element'; import { decodeEntities } from '@wordpress/html-entities'; -import { useDispatch } from '@wordpress/data'; +import { useDispatch, useSelect } from '@wordpress/data'; /** * Internal dependencies @@ -22,10 +22,25 @@ const FrontendBlock = ( { } ): JSX.Element | null => { const { cartItems, cartIsLoading, cartItemErrors } = useStoreCart(); const { hasDarkControls } = useCartBlockContext(); - const { createErrorNotice } = useDispatch( 'core/notices' ); + const { createErrorNotice, removeNotice } = useDispatch( 'core/notices' ); + + const currentlyDisplayedErrorNoticeCodes = useSelect( ( select ) => { + return select( 'core/notices' ) + .getNotices( 'wc/cart' ) + .filter( + ( notice ) => + notice.status === 'error' && notice.type === 'default' + ) + .map( ( notice ) => notice.id ); + } ); - // Ensures any cart errors listed in the API response get shown. useEffect( () => { + // Clear errors out of the store before adding the new ones from the response. + currentlyDisplayedErrorNoticeCodes.forEach( ( id ) => { + removeNotice( id, 'wc/cart' ); + } ); + + // Ensures any cart errors listed in the API response get shown. cartItemErrors.forEach( ( error ) => { createErrorNotice( decodeEntities( error.message ), { isDismissible: true,