login-hooks.ts
Overview
login-hooks.ts provides a collection of React hooks designed to manage user authentication workflows within a React application. These hooks encapsulate the login, logout, registration processes, and retrieval of login channels, while integrating with backend services and handling authorization tokens. The file leverages @tanstack/react-query for asynchronous data fetching and mutation management, antd for form handling, and i18next for internationalized messages.
The primary purpose of this file is to abstract the complexities of authentication logic into reusable hooks that can be easily integrated into React components, promoting modularity and maintainability.
Detailed Explanation of Exports
Interfaces
ILoginRequestBody
export interface ILoginRequestBody {
email: string;
password: string;
}
Description: Defines the shape of the login request payload.
Properties:
email: User's email address.password: User's password.
IRegisterRequestBody
export interface IRegisterRequestBody extends ILoginRequestBody {
nickname: string;
}
Description: Extends
ILoginRequestBodyto include a nickname, used for user registration.Properties:
Inherits
emailandpassword.nickname: User's display name or nickname.
ILoginChannel
export interface ILoginChannel {
channel: string;
display_name: string;
icon: string;
}
Description: Represents an external or internal login channel (e.g., Google, Facebook).
Properties:
channel: Identifier for the channel.display_name: User-friendly name of the channel.icon: Icon associated with the channel.
Hooks
useLoginChannels
export const useLoginChannels = () => { ... }
Purpose: Fetches the list of available login channels from the backend.
Returns:
channels: Array ofILoginChannelobjects.loading: Boolean indicating loading state.
Implementation Details:
Uses
useQueryfrom React Query with key'loginChannels'.Calls the
getLoginChannelsservice to asynchronously fetch data.Defaults to an empty array if no data is available.
Usage Example:
const { channels, loading } = useLoginChannels();
if (loading) return <Spinner />;
return (
<ul>
{channels.map(ch => (
<li key={ch.channel}>{ch.display_name}</li>
))}
</ul>
);
useLoginWithChannel
export const useLoginWithChannel = () => { ... }
Purpose: Initiates login through a selected external login channel.
Returns:
loading: Boolean indicating whether the login request is in progress.login: Async function accepting achannelstring to trigger login.
Implementation Details:
Uses
useMutationwith key'loginWithChannel'.Calls
loginWithChannel(channel), which likely initiates OAuth or similar flow.Resolves immediately afterward (no direct response expected here).
Usage Example:
const { loading, login } = useLoginWithChannel();
<button disabled={loading} onClick={() => login('google')}>
Login with Google
</button>;
useLogin
export const useLogin = () => { ... }
Purpose: Handles user login by submitting credentials and storing authentication tokens.
Returns:
data: Response code from login API.loading: Boolean indicating whether login is in progress.login: Async mutation function accepting{ email, password }.
Parameters of
login:Object with
email(string) andpassword(string).
Implementation Details:
Calls
userService.login(params)to authenticate.On success (
res.code === 0), extracts:Authorization token from response headers.
User info (
avatar,nickname,email) from response data.
Stores these in
authorizationUtilfor future authenticated requests.
**Returns response code for further handling.
Usage Example:
const { data, loading, login } = useLogin();
const handleSubmit = async (values: ILoginRequestBody) => {
const code = await login(values);
if (code === 0) {
// Successfully logged in
} else {
// Handle error
}
};
useRegister
export const useRegister = () => { ... }
Purpose: Handles user registration.
Returns:
data: Response code from registration API.loading: Boolean indicating registration progress.register: Async mutation function accepting{ email, password, nickname }.
Parameters of
register:Object with
email(string),password(string), andnickname(string).
Implementation Details:
Calls
userService.register(params)to create a new user.On success (
data.code === 0), displays a success message.If registration is disabled (detected by checking message string), shows an error notification.
**Messages are localized using
useTranslation.Usage Example:
const { data, loading, register } = useRegister();
const onRegister = async (values: IRegisterRequestBody) => {
const code = await register(values);
if (code === 0) {
// Registration successful
}
};
useLogout
export const useLogout = () => { ... }
Purpose: Logs the user out and clears stored authorization.
Returns:
data: Response code from logout API.loading: Boolean indicating logout progress.logout: Async mutation function with no parameters.
Implementation Details:
Calls
userService.logout().On success (
data.code === 0), shows success message, clears all authorization data viaauthorizationUtil.removeAll(), and redirects user to the login page usingredirectToLogin.
**Messages are localized with
useTranslation.Usage Example:
const { data, loading, logout } = useLogout();
const handleLogout = async () => {
const code = await logout();
if (code === 0) {
// User logged out successfully
}
};
useHandleSubmittable
export const useHandleSubmittable = (form: FormInstance) => { ... }
Purpose: Provides a reactive boolean indicating whether a given Ant Design form is currently valid and submittable.
Parameters:
form: An instance of Ant Design'sFormInstance.
Returns:
submittable: Boolean that istrueif form validation passes, otherwisefalse.
Implementation Details:
Uses
Form.useWatchto watch all form values.Uses
useEffectto validate fields on every change.Sets
submittablebased on validation success.
Use Case: Enable or disable submit buttons based on form validity.
Usage Example:
const [form] = Form.useForm();
const { submittable } = useHandleSubmittable(form);
return (
<Form form={form}>
{/* form items */}
<Button type="primary" disabled={!submittable}>Submit</Button>
</Form>
);
Important Implementation Details and Algorithms
React Query Integration: All asynchronous operations (fetching channels, login, register, logout) are handled via React Query's
useQueryanduseMutationhooks, providing built-in caching, loading states, and error handling paradigms.Authorization Token Management: After successful login, the access token and authorization header are stored using
authorizationUtil.setItems, abstracting local storage or cookie management.Internationalization: User feedback messages utilize
react-i18nextfor localization, allowing for multi-language support.Form Validation Handling: The
useHandleSubmittablehook leverages Ant Design's form validation to dynamically track if a form can be submitted.Login Channels: Supports multiple login channels (possibly OAuth providers), abstracted through
useLoginChannelsanduseLoginWithChannel.
Interaction with Other Parts of the System
@/services/user-service: Contains the API calls for user operations such as login, logout, register, and fetching login channels.@/utils/authorization-util: Utility for managing authorization tokens and user info.@/components/ui/message: UI component for showing success or error messages.antd: Ant Design UI framework used for form management.React Query: Manages server state and asynchronous requests.
i18next: Provides internationalization support for messages.
This file acts as the business logic layer between UI components (login forms, registration forms, logout buttons) and backend services, providing clean hooks to be consumed by UI components.
Mermaid Diagram: Flowchart of Main Functions and Their Relationships
flowchart TD
A[useLoginChannels] -->|fetches| B[getLoginChannels API]
C[useLoginWithChannel] -->|initiates| D[loginWithChannel Service]
E[useLogin] -->|calls| F[userService.login API]
E -->|stores tokens| G[authorizationUtil.setItems]
H[useRegister] -->|calls| I[userService.register API]
H -->|shows messages| J[message UI]
K[useLogout] -->|calls| L[userService.logout API]
K -->|clears auth| M[authorizationUtil.removeAll]
K -->|redirects| N[redirectToLogin]
O[useHandleSubmittable] -->|watches| P[AntD Form]
P -->|validateFields| Q[form validation]
style A fill:#bbdefb,stroke:#1e88e5
style C fill:#bbdefb,stroke:#1e88e5
style E fill:#bbdefb,stroke:#1e88e5
style H fill:#bbdefb,stroke:#1e88e5
style K fill:#bbdefb,stroke:#1e88e5
style O fill:#c8e6c9,stroke:#388e3c
Summary
login-hooks.ts is a utility file that exports React hooks to handle authentication-related actions in a modular and maintainable way. It encapsulates API communication, token management, UI feedback, and form validation into easy-to-use hooks that can be consumed by React components in the application. Its integration with React Query, Ant Design, and i18next makes it a robust and internationalized solution for login workflows.