fix: guard useAuth against unmount race, return error from logout

This commit is contained in:
2026-05-07 20:11:23 +03:00
parent 418b4b7cac
commit f6b66efd02
2 changed files with 28 additions and 4 deletions
+16
View File
@@ -96,4 +96,20 @@ describe('useAuth', () => {
unmount();
expect(mockUnsubscribe).toHaveBeenCalled();
});
it('updates session when onAuthStateChange fires', async () => {
let authCallback;
mockOnAuthStateChange.mockImplementation((cb) => {
authCallback = cb;
return { data: { subscription: { unsubscribe: mockUnsubscribe } } };
});
const newSession = { user: { email: 'other@test.com' } };
mockGetSession.mockResolvedValue({ data: { session: null } });
const { result } = renderHook(() => useAuth());
await act(async () => {});
act(() => {
authCallback('SIGNED_IN', newSession);
});
expect(result.current.session).toEqual(newSession);
});
});
+12 -4
View File
@@ -6,16 +6,23 @@ export function useAuth() {
const [loading, setLoading] = useState(true);
useEffect(() => {
let active = true;
supabase.auth.getSession().then(({ data: { session } }) => {
setSession(session);
setLoading(false);
if (active) {
setSession(session);
setLoading(false);
}
});
const { data: { subscription } } = supabase.auth.onAuthStateChange((_event, session) => {
setSession(session);
});
return () => subscription.unsubscribe();
return () => {
active = false;
subscription.unsubscribe();
};
}, []);
const login = async (email, password) => {
@@ -24,7 +31,8 @@ export function useAuth() {
};
const logout = async () => {
await supabase.auth.signOut();
const { error } = await supabase.auth.signOut();
return { error };
};
return { session, loading, login, logout };