Skip to content

Commit

Permalink
add ensureSignedIn option to useAuth hook (#176)
Browse files Browse the repository at this point in the history
  • Loading branch information
nicknisi authored Jan 15, 2025
1 parent ce5f0a3 commit eed18ef
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 1 deletion.
28 changes: 28 additions & 0 deletions __tests__/authkit-provider.spec.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -165,6 +165,34 @@ describe('AuthKitProvider', () => {
});

describe('useAuth', () => {
beforeEach(() => {
jest.clearAllMocks();
});

it('should call getAuth when a user is not returned when ensureSignedIn is true', async () => {
// First and second calls return no user, second call returns a user
(getAuthAction as jest.Mock)
.mockResolvedValueOnce({ user: null, loading: true })
.mockResolvedValueOnce({ user: { email: '[email protected]' }, loading: false });

const TestComponent = () => {
const auth = useAuth({ ensureSignedIn: true });
return <div data-testid="email">{auth.user?.email}</div>;
};

const { getByTestId } = render(
<AuthKitProvider>
<TestComponent />
</AuthKitProvider>,
);

await waitFor(() => {
expect(getAuthAction).toHaveBeenCalledTimes(2);
expect(getAuthAction).toHaveBeenLastCalledWith(true);
expect(getByTestId('email')).toHaveTextContent('[email protected]');
});
});

it('should throw error when used outside of AuthKitProvider', () => {
const TestComponent = () => {
const auth = useAuth();
Expand Down
10 changes: 9 additions & 1 deletion src/components/authkit-provider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -160,10 +160,18 @@ export const AuthKitProvider = ({ children, onSessionExpired }: AuthKitProviderP
);
};

export function useAuth() {
export function useAuth({ ensureSignedIn = false }: { ensureSignedIn?: boolean } = {}) {
const context = useContext(AuthContext);

useEffect(() => {
if (context && ensureSignedIn && !context.user && !context.loading) {
context.getAuth({ ensureSignedIn });
}
}, [ensureSignedIn, context?.user, context?.loading, context?.getAuth]);

if (!context) {
throw new Error('useAuth must be used within an AuthKitProvider');
}

return context;
}

0 comments on commit eed18ef

Please sign in to comment.