fix: repeat API request in update token

This commit is contained in:
Tristan Yang
2022-08-16 18:01:38 +08:00
parent 4d25c5a384
commit 63f16e6117
2 changed files with 17 additions and 19 deletions
+15 -17
View File
@@ -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) => {
@@ -5,7 +5,7 @@ import { firebaseConfig } from "../../../app/config";
let requesting = false;
let error = false;
const useDeviceToken = (vapidKey: string) => {
const [token, setToken] = useState<string | null>(null);
const [token, setToken] = useState<string>("");
// 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;