Stabilize mobile auth session handling
This commit is contained in:
@@ -1,12 +1,18 @@
|
||||
import { useEffect, useRef } from "react";
|
||||
import { AppState, type AppStateStatus } from "react-native";
|
||||
|
||||
import { useSession } from "@/contexts/AuthContext";
|
||||
import { useAccounts } from "@/contexts/AccountsContext";
|
||||
import { useAuthClient, useSession } from "@/contexts/AuthContext";
|
||||
import { performAuthReset } from "@/lib/auth-session";
|
||||
import { isRateLimitError } from "@/lib/trpc-errors";
|
||||
|
||||
/** Refetch auth session when the app returns to the foreground. */
|
||||
export function SessionSync() {
|
||||
const { refetch } = useSession();
|
||||
const authClient = useAuthClient();
|
||||
const { activeAccountId, clearActiveAccount } = useAccounts();
|
||||
const { data: session, refetch } = useSession();
|
||||
const wasBackgrounded = useRef(false);
|
||||
const resettingRef = useRef(false);
|
||||
|
||||
useEffect(() => {
|
||||
const subscription = AppState.addEventListener("change", (nextState: AppStateStatus) => {
|
||||
@@ -17,11 +23,30 @@ export function SessionSync() {
|
||||
|
||||
if (nextState !== "active" || !wasBackgrounded.current) return;
|
||||
wasBackgrounded.current = false;
|
||||
void refetch();
|
||||
|
||||
void (async () => {
|
||||
await refetch();
|
||||
const next = await authClient.getSession();
|
||||
if (next.error && isRateLimitError(next.error)) return;
|
||||
if (next.data?.user) return;
|
||||
if (!session?.user || resettingRef.current) return;
|
||||
|
||||
resettingRef.current = true;
|
||||
try {
|
||||
await performAuthReset({
|
||||
authClient,
|
||||
clearActiveAccount,
|
||||
activeAccountId,
|
||||
refetchSession: refetch,
|
||||
});
|
||||
} finally {
|
||||
resettingRef.current = false;
|
||||
}
|
||||
})();
|
||||
});
|
||||
|
||||
return () => subscription.remove();
|
||||
}, [refetch]);
|
||||
}, [authClient, refetch, session?.user, activeAccountId, clearActiveAccount]);
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user