From b5b84861054151c56301cc756a05cf29a4a07fda Mon Sep 17 00:00:00 2001 From: Xiao Yijun Date: Wed, 7 Jun 2023 11:29:37 +0800 Subject: [PATCH] fix(console): close confirm modal on the location path changed (#3981) --- .../contexts/AppConfirmModalProvider/index.tsx | 18 +++++++++++++++++- .../console/src/pages/WebhookDetails/index.tsx | 10 ++-------- 2 files changed, 19 insertions(+), 9 deletions(-) diff --git a/packages/console/src/contexts/AppConfirmModalProvider/index.tsx b/packages/console/src/contexts/AppConfirmModalProvider/index.tsx index fc3a86645..814c979b1 100644 --- a/packages/console/src/contexts/AppConfirmModalProvider/index.tsx +++ b/packages/console/src/contexts/AppConfirmModalProvider/index.tsx @@ -1,6 +1,6 @@ import type { Nullable } from '@silverhand/essentials'; import { noop } from '@silverhand/essentials'; -import { useState, useRef, useMemo, createContext, useCallback } from 'react'; +import { useState, useRef, useMemo, createContext, useCallback, useEffect } from 'react'; import ConfirmModal from '@/components/ConfirmModal'; import type { ConfirmModalProps } from '@/components/ConfirmModal'; @@ -85,6 +85,22 @@ function AppConfirmModalProvider({ children }: Props) { [handleCancel, handleConfirm, handleShow] ); + useEffect(() => { + const handlePathChange = () => { + handleCancel(); + }; + + /** + * Note: Close the modal when the location path changes. + * We don't use react-router-dom's `UseLocation` since this is a global component and not relying on the router. + */ + window.addEventListener('popstate', handlePathChange); + + return () => { + window.removeEventListener('popstate', handlePathChange); + }; + }, [handleCancel]); + const { ModalContent, type, ...restProps } = modalState; return ( diff --git a/packages/console/src/pages/WebhookDetails/index.tsx b/packages/console/src/pages/WebhookDetails/index.tsx index c7ae3c5ca..ae8cb7b69 100644 --- a/packages/console/src/pages/WebhookDetails/index.tsx +++ b/packages/console/src/pages/WebhookDetails/index.tsx @@ -1,7 +1,7 @@ import { withAppInsights } from '@logto/app-insights/react'; import { type HookResponse, type Hook } from '@logto/schemas'; import classNames from 'classnames'; -import { useEffect, useState } from 'react'; +import { useState } from 'react'; import { toast } from 'react-hot-toast'; import { useTranslation } from 'react-i18next'; import { Outlet, useLocation, useNavigate, useParams } from 'react-router-dom'; @@ -48,17 +48,11 @@ function WebhookDetails() { const theme = useTheme(); const WebhookIcon = theme === 'light' ? Webhook : WebhookDark; - const { show, cancel } = useConfirmModal(); + const { show } = useConfirmModal(); const [isDeleting, setIsDeleting] = useState(false); const [isUpdatingEnableState, setIsUpdatingEnableState] = useState(false); - useEffect(() => { - return () => { - cancel(); - }; - }, [cancel, pathname]); - const handleDelete = async () => { if (!data || isDeleting) { return;