Skip to content

Commit baf469e

Browse files
sketch
1 parent 2209123 commit baf469e

File tree

1 file changed

+46
-2
lines changed

1 file changed

+46
-2
lines changed

src/react/ConvexAuthState.tsx

Lines changed: 46 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import React, {
33
ReactNode,
44
useContext,
55
useEffect,
6+
useRef,
67
useState,
78
} from "react";
89
import { AuthTokenFetcher } from "../browser/sync/client.js";
@@ -207,11 +208,54 @@ function ConvexAuthStateLastEffect({
207208
React.SetStateAction<boolean | null>
208209
>;
209210
}) {
211+
// Store information about *future* render, future from the perspective of
212+
// the cleanup function below that needs it.
213+
const isUnmountingRef = useRef(false);
214+
useEffect(
215+
() => () => {
216+
isUnmountingRef.current = true;
217+
},
218+
[],
219+
);
220+
const futureValuesRef = useRef({
221+
authProviderAuthenticated,
222+
client,
223+
authProviderLoading,
224+
});
225+
futureValuesRef.current = {
226+
authProviderAuthenticated,
227+
client,
228+
authProviderLoading,
229+
};
230+
210231
useEffect(() => {
211-
// If rendered with authProviderAuthenticated=true then clear that auth on in cleanup.
232+
// Capture the values from when this effect was set up
233+
const effectClient = client;
234+
const effectAuthProviderLoading = authProviderLoading;
235+
236+
// If rendered with authProviderAuthenticated=true then clear that auth on cleanup if needed.
212237
if (authProviderAuthenticated) {
213238
return () => {
214-
client.clearAuth();
239+
// Get the "future" values which triggered this cleanup
240+
if (isUnmountingRef.current) {
241+
client.clearAuth();
242+
return;
243+
}
244+
245+
const future = futureValuesRef.current;
246+
const clientChanged = effectClient !== future.client;
247+
const authProviderWentBackToLoading =
248+
!effectAuthProviderLoading && future.authProviderLoading;
249+
250+
const shouldClearAuth =
251+
!future.authProviderAuthenticated ||
252+
clientChanged ||
253+
authProviderWentBackToLoading;
254+
255+
if (shouldClearAuth) {
256+
client.clearAuth();
257+
}
258+
215259
// Set state back to loading in case this is a transition from one
216260
// fetchToken function to another which signals a new auth context,
217261
// e.g. a new orgId from Clerk. Auth context changes like this

0 commit comments

Comments
 (0)