From 63f16e61174e18a4d0a887090aa76e2ea8f2d2d9 Mon Sep 17 00:00:00 2001 From: Tristan Yang Date: Tue, 16 Aug 2022 18:01:38 +0800 Subject: [PATCH] fix: repeat API request in update token --- src/common/component/Notification/index.tsx | 32 +++++++++---------- .../component/Notification/useDeviceToken.ts | 4 +-- 2 files changed, 17 insertions(+), 19 deletions(-) diff --git a/src/common/component/Notification/index.tsx b/src/common/component/Notification/index.tsx index b3defe63..319598fd 100644 --- a/src/common/component/Notification/index.tsx +++ b/src/common/component/Notification/index.tsx @@ -4,27 +4,25 @@ import useDeviceToken from "./useDeviceToken"; import { vapidKey } from "../../../app/config"; import { useUpdateDeviceTokenMutation } from "../../../app/services/auth"; let updated = false; +let updating = false; const Notification = () => { const navigateTo = useNavigate(); const token = useDeviceToken(vapidKey); - const [updateDeviceToken, { isLoading, isSuccess }] = useUpdateDeviceTokenMutation(); + const [updateDeviceToken] = useUpdateDeviceTokenMutation(); useEffect(() => { - if (token && !isLoading && !updated) { - updateDeviceToken(token) - .then(() => { - updated = true; - }) - .catch(() => { - updated = true; - }) - .finally(() => { - updated = true; - }); - } - }, [token, isLoading]); - useEffect(() => { - updated = isSuccess; - }, [isSuccess]); + const updateToken = async (token: string) => { + if (!token || updating || updated) return; + try { + updating = true; + await updateDeviceToken(token); + updated = true; + } catch { + updating = false; + updated = true; + } + }; + updateToken(token as string); + }, [token]); useEffect(() => { const handleServiceworkerMessage = (event: MessageEvent) => { diff --git a/src/common/component/Notification/useDeviceToken.ts b/src/common/component/Notification/useDeviceToken.ts index 15e74d22..3a68544b 100644 --- a/src/common/component/Notification/useDeviceToken.ts +++ b/src/common/component/Notification/useDeviceToken.ts @@ -5,7 +5,7 @@ import { firebaseConfig } from "../../../app/config"; let requesting = false; let error = false; const useDeviceToken = (vapidKey: string) => { - const [token, setToken] = useState(null); + const [token, setToken] = useState(""); // https only if (navigator.serviceWorker) { const messaging = getMessaging(initializeApp(firebaseConfig)); @@ -32,7 +32,7 @@ const useDeviceToken = (vapidKey: string) => { console.log("An error occurred while retrieving token. ", err); }); } - return token; + return token as string; }; export default useDeviceToken;