fix: guard useAuth against unmount race, return error from logout
This commit is contained in:
@@ -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);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -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 };
|
||||
|
||||
Reference in New Issue
Block a user