Skip to content

Commit

Permalink
feat(user): remove anonymous user from localstorage if it's removed
Browse files Browse the repository at this point in the history
  • Loading branch information
ygrishajev committed Jan 2, 2025
1 parent 8e65fc2 commit 532f26e
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 3 deletions.
8 changes: 7 additions & 1 deletion apps/deploy-web/src/hooks/useStoredAnonymousUser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
7 changes: 5 additions & 2 deletions apps/deploy-web/src/queries/useAnonymousUserQuery.ts
Original file line number Diff line number Diff line change
@@ -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";
Expand All @@ -19,16 +20,18 @@ 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 {
const { data: fetched, ...rest } = await userHttpService.getOrCreateAnonymousUser(id);
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 });
}
});

Expand Down

0 comments on commit 532f26e

Please sign in to comment.