diff --git a/apps/deploy-web/src/hooks/useStoredAnonymousUser.ts b/apps/deploy-web/src/hooks/useStoredAnonymousUser.ts index 5f9fa3a98..d9c3bc9a9 100644 --- a/apps/deploy-web/src/hooks/useStoredAnonymousUser.ts +++ b/apps/deploy-web/src/hooks/useStoredAnonymousUser.ts @@ -16,10 +16,16 @@ const storedAnonymousUser: UserOutput | undefined = storedAnonymousUserStr ? JSO export const useStoredAnonymousUser = (): UseApiUserResult => { const { user: registeredUser, isLoading: isLoadingRegisteredUser } = useCustomUser(); - const { user, isLoading, token } = useAnonymousUserQuery(storedAnonymousUser?.id, { + const { user, isLoading, token, error } = useAnonymousUserQuery(storedAnonymousUser?.id, { enabled: browserEnvConfig.NEXT_PUBLIC_BILLING_ENABLED && !registeredUser && !isLoadingRegisteredUser }); + useWhen(storedAnonymousUser && !storedAnonymousUser.userId && error && "status" in error && error.status === 401, () => { + localStorage.removeItem(ANONYMOUS_USER_KEY); + localStorage.removeItem(ANONYMOUS_USER_TOKEN_KEY); + window.location.reload(); + }); + useWhen(user, () => localStorage.setItem("anonymous-user", JSON.stringify(user))); useWhen(registeredUser?.id, () => { localStorage.removeItem(ANONYMOUS_USER_KEY); diff --git a/apps/deploy-web/src/queries/useAnonymousUserQuery.ts b/apps/deploy-web/src/queries/useAnonymousUserQuery.ts index 5f05edaaf..dacf1f145 100644 --- a/apps/deploy-web/src/queries/useAnonymousUserQuery.ts +++ b/apps/deploy-web/src/queries/useAnonymousUserQuery.ts @@ -1,5 +1,6 @@ import { useState } from "react"; import * as Sentry from "@sentry/nextjs"; +import { AxiosError } from "axios"; import { useWhen } from "@src/hooks/useWhen"; import { userHttpService } from "@src/services/http/http-browser.service"; @@ -19,7 +20,9 @@ export interface UserOutput { } export function useAnonymousUserQuery(id?: string, options?: { enabled?: boolean }) { - const [userState, setUserState] = useState<{ user?: UserOutput; isLoading: boolean; token?: string }>({ isLoading: !!options?.enabled }); + const [userState, setUserState] = useState<{ user?: UserOutput; isLoading: boolean; token?: string; error?: Error | AxiosError }>({ + isLoading: !!options?.enabled + }); useWhen(options?.enabled && !userState.user, async () => { try { @@ -27,8 +30,8 @@ export function useAnonymousUserQuery(id?: string, options?: { enabled?: boolean const token = "token" in rest ? rest.token : undefined; setUserState({ user: fetched, token, isLoading: false }); } catch (error) { + setUserState({ isLoading: false, error }); Sentry.captureException(error); - setUserState({ isLoading: false }); } });