Skip to Content

signIn, signInWith

signIn stores the token and the user after sign-in. signInWith opens a Google sign-in window and calls signIn when it finishes.

Usage

app/login/page.tsx
import { useNavigate } from "react-router-dom"; import { Button } from "antd"; import { LoginForm, ProFormText } from "@ant-design/pro-components"; import { useApiClient } from "app/api"; import { signIn, signInWith } from "app/hooks"; export default function LoginPage() { const api = useApiClient(); const nav = useNavigate(); return ( <LoginForm title="Sign in" onFinish={async (values) => { signIn(await api.auth.login(values)); nav("/"); return true; }} actions={<Button block onClick={async () => { await signInWith("google"); nav("/"); }}>Sign in with Google</Button>} > <ProFormText name="email" placeholder="Email" rules={[{ required: true }]} /> <ProFormText.Password name="password" placeholder="Password" rules={[{ required: true }]} /> </LoginForm> ); }

Signature

app/hooks.ts
type SessionUser = { id: number; name: string; email: string; role: string; avatarUrl?: string | null }; function signIn(res: { token: string; user: SessionUser }): void; function signInWith(provider: string): Promise<{ token: string; user: SessionUser }>;

Parameters

  • res (signIn): the { token, user } result of a sign-in API. api.auth.login(values) and api.auth.register(values), generated from app/auth.ts, both return this shape; your own sign-in API works too if it returns the same shape.
  • provider (signInWith): the sign-in method; "google" is the one available. Needs providers: ["google"] in app/auth.ts.

Returns

signIn returns nothing. It stores the token (from then on every call through useApiClient() and useApi() sends Authorization: Bearer <token>), stores the user, then tells every useSession to re-render.

signInWith resolves { token, user } once the user is signed in; signIn has already run by then. The promise rejects when the user closes the sign-in window or Google reports an error; the message is at e.response.data.message, like an API error.

Examples

When the browser blocks the popup, signInWith sends the whole page to Google. On the way back the page finishes signing in by itself; the promise never settles in that case, so don’t wait on it for anything else.

app/components/google-button.tsx
const { message } = App.useApp(); async function google() { try { await signInWith("google"); nav("/"); } catch (e: any) { message.error(e.response?.data?.message ?? "Could not sign in"); } }

The /login and /register pages of the auth block already have the Google button. Call signInWith when you build your own sign-in screen.

Next steps

Last updated