user-setting-hooks.tsx
Overview
The user-setting-hooks.tsx file provides a comprehensive suite of custom React hooks designed to manage user settings, tenant information, system tokens, and related functionalities in a React application. It primarily utilizes React Query for asynchronous data fetching and mutations, integrates i18n for translations, and leverages Ant Design components for UI interactions such as modals and messages.
These hooks abstract away the complexity of API interactions through the userService, ensuring that components consuming these hooks can easily fetch, update, and manipulate user and system-related data. The file enables seamless management of user info, tenant info, system status, tokens, and Langfuse configurations with built-in feedback and cache invalidation.
Detailed Explanations
Imports and Dependencies
React Query (
useQuery,useMutation,useQueryClient): For data fetching, caching, and mutations.Ant Design (
Modal): For warning modals.DOMPurify: To sanitize HTML content in modals.
Lodash (
isEmpty): Utility for emptiness checks.React hooks:
useCallback,useMemo,useState.i18next (
useTranslation): For internationalization and language management.Umi (
history): For navigation.userService and related service functions: Abstraction over backend API calls.
Various TypeScript interfaces describing data shapes.
Hook-by-Hook Breakdown
1. useFetchUserInfo
Fetches the current user information.
Returns:
data:IUserInfoobject representing user details.loading: boolean indicating fetch status.
Behavior:
Fetches user info from the backend.
On success, changes application language (
i18n.changeLanguage) based on user preference.
Usage:
const { data: userInfo, loading } = useFetchUserInfo();
2. useFetchTenantInfo
Fetches tenant-related information.
Parameters:
showEmptyModelWarn(optional, defaultfalse): Whether to show a warning modal if model IDs are missing.
Returns:
data:ITenantInfoobject.loading: boolean.
Behavior:
Retrieves tenant info including IDs for chat and speech-to-text models.
Optionally shows a warning modal if critical model IDs are missing.
Adds aliases
chat_idandspeech2text_idforllm_idandasr_idrespectively.
Usage:
const { data: tenantInfo, loading } = useFetchTenantInfo(true);
3. useSelectParserList
Generates a list of parsers for use in dropdowns or selectors.
Returns: An array of objects
{ value: string; label: string }.Behavior:
Parses the
parser_idsstring from tenant info.Splits by comma, then by colon to separate id and label.
Usage:
const parserList = useSelectParserList();
// [{ value: 'id1', label: 'Parser 1' }, ...]
4. useSaveSetting
Saves user settings or password changes.
Returns:
data: Result code from API.loading: boolean.saveSetting: function to trigger save mutation.
Parameters for mutation function:
Partial
IUserInfoor object withnew_password.
Behavior:
Calls the user settings API.
On success, shows success message and invalidates
userInfocache.
Usage:
const { saveSetting, loading } = useSaveSetting();
await saveSetting({ new_password: 'newPass123' });
5. useFetchSystemVersion
Fetches the current system version.
Returns:
version: string representing system version.loading: boolean.fetchSystemVersion: function to trigger fetch.
Behavior:
Uses internal state and
useCallbackfor fetch.
Usage:
const { version, loading, fetchSystemVersion } = useFetchSystemVersion();
fetchSystemVersion();
6. useFetchSystemStatus
Fetches the system status.
Returns:
systemStatus:ISystemStatusobject.loading: boolean.fetchSystemStatus: function to trigger fetch.
Usage:
const { systemStatus, loading, fetchSystemStatus } = useFetchSystemStatus();
fetchSystemStatus();
7. useFetchManualSystemTokenList
Manually fetches system tokens via mutation.
Returns:
data: Array ofIToken.loading: boolean.fetchSystemTokenList: function to trigger fetch.
Usage:
const { data: tokens, fetchSystemTokenList } = useFetchManualSystemTokenList();
fetchSystemTokenList();
8. useFetchSystemTokenList
Fetches system tokens automatically.
Returns:
data: Array ofIToken.loading: boolean.refetch: function to re-fetch tokens.
Usage:
const { data: tokens, loading, refetch } = useFetchSystemTokenList();
9. useRemoveSystemToken
Removes a system token by token string.
Returns:
data: API response data.loading: boolean.removeToken: function accepting a token string.
Behavior:
Calls API to remove token.
On success, shows deletion message and invalidates token list cache.
Usage:
const { removeToken } = useRemoveSystemToken();
await removeToken('token-string');
10. useCreateSystemToken
Creates a new system token.
Returns:
data: API response data.loading: boolean.createToken: function accepting parameters.
Behavior:
Calls API to create token.
On success, invalidates token list.
Usage:
const { createToken } = useCreateSystemToken();
await createToken({ name: 'New Token' });
11. useListTenantUser
Lists users associated with the current tenant.
Returns:
data: Array ofITenantUser.loading: boolean.refetch: function.
Behavior:
Depends on current tenant ID; query is enabled only if tenant ID is present.
Usage:
const { data: tenantUsers, loading, refetch } = useListTenantUser();
12. useAddTenantUser
Adds a new user to the tenant via email.
Returns:
data: API result code.loading: boolean.addTenantUser: function accepting user email.
Behavior:
On success, invalidates tenant user list cache.
Usage:
const { addTenantUser } = useAddTenantUser();
await addTenantUser('[email protected]');
13. useDeleteTenantUser
Deletes a user from the tenant.
Returns:
data: API response.loading: boolean.deleteTenantUser: function accepting{ userId, tenantId? }.
Behavior:
On success, shows deletion message and invalidates tenant user and tenant lists.
Usage:
const { deleteTenantUser } = useDeleteTenantUser();
await deleteTenantUser({ userId: '12345' });
14. useListTenant
Lists tenants.
Returns:
data: Array ofITenant.loading: boolean.refetch: function.
Behavior:
Query only enabled if tenant ID from tenant info is present.
Usage:
const { data: tenants, loading, refetch } = useListTenant();
15. useAgreeTenant
Agrees (consents) to a tenant.
Returns:
data: API response data.loading: boolean.agreeTenant: function accepting tenant ID string.
Behavior:
On success, shows success message and invalidates tenant list cache.
Usage:
const { agreeTenant } = useAgreeTenant();
await agreeTenant('tenantId123');
16. useSetLangfuseConfig
Sets Langfuse configuration.
Returns:
data: API result code.loading: boolean.setLangfuseConfig: mutation function.
Parameters:
ISetLangfuseConfigRequestBodyobject with config details.
Behavior:
On success, shows operation success message.
Usage:
const { setLangfuseConfig } = useSetLangfuseConfig();
await setLangfuseConfig({ enabled: true });
17. useDeleteLangfuseConfig
Deletes Langfuse configuration.
Returns:
data: API result code.loading: boolean.deleteLangfuseConfig: mutation function.
Behavior:
On success, shows deletion message.
Usage:
const { deleteLangfuseConfig } = useDeleteLangfuseConfig();
await deleteLangfuseConfig();
18. useFetchLangfuseConfig
Fetches Langfuse configuration.
Returns:
data:ILangfuseConfigobject.loading: boolean.
Usage:
const { data: langfuseConfig, loading } = useFetchLangfuseConfig();
Important Implementation Details
React Query Integration:
All asynchronous operations are wrapped withuseQueryoruseMutationhooks from React Query, providing loading states, cache management, and mutation capabilities with automatic invalidation.Internationalization (i18n):
Hooks leverageuseTranslationfor UI messages and language changes, ensuring localized user feedback.Modal and Message UI:
Use of Ant Design'sModal.warningfor warnings andmessage.successfor success feedback to users.Cache Invalidation:
After mutations that modify data (e.g., adding/removing tenants or tokens), queries are invalidated to keep UI data consistent.Sanitization:
DOMPurifyis used to sanitize HTML content in modals to prevent XSS attacks.Conditional Queries:
Some hooks enable queries conditionally based on the availability of tenant IDs to prevent unnecessary API calls.
Interaction with Other Parts of the System
Services Layer (
userService):
All API calls are routed through theuserServicemodule and related service functions, which act as a client to the backend REST API.UI Components:
Components consuming these hooks can seamlessly display user and tenant info, system tokens, and configurations, and perform CRUD operations with minimal boilerplate.Routing (
historyfrom Umi):
Used to navigate users to specific pages (e.g., redirecting to model settings on warnings).Global State and Cache:
React Query manages caching and state sync among components using these hooks.
Usage Example
import React from 'react';
import { useFetchUserInfo, useSaveSetting } from './user-setting-hooks';
const UserProfile: React.FC = () => {
const { data: userInfo, loading } = useFetchUserInfo();
const { saveSetting, loading: saving } = useSaveSetting();
const onChangePassword = async () => {
await saveSetting({ new_password: 'newSecret123' });
};
if (loading) return <div>Loading...</div>;
return (
<div>
<p>User: {userInfo.name}</p>
<button onClick={onChangePassword} disabled={saving}>
Change Password
</button>
</div>
);
};
Visual Diagram
flowchart TD
A[useFetchUserInfo] -->|fetches| B[userService.user_info]
C[useFetchTenantInfo] -->|fetches| D[userService.get_tenant_info]
E[useSaveSetting] -->|mutates| F[userService.setting]
G[useFetchSystemVersion] -->|fetches| H[userService.getSystemVersion]
I[useFetchSystemStatus] -->|fetches| J[userService.getSystemStatus]
K[useFetchSystemTokenList] -->|fetches| L[userService.listToken]
M[useRemoveSystemToken] -->|mutates| N[userService.removeToken]
O[useCreateSystemToken] -->|mutates| P[userService.createToken]
Q[useListTenantUser] -->|fetches| R[listTenantUser]
S[useAddTenantUser] -->|mutates| T[addTenantUser]
U[useDeleteTenantUser] -->|mutates| V[deleteTenantUser]
W[useListTenant] -->|fetches| X[listTenant]
Y[useAgreeTenant] -->|mutates| Z[agreeTenant]
AA[useSetLangfuseConfig] -->|mutates| AB[userService.setLangfuseConfig]
AC[useDeleteLangfuseConfig] -->|mutates| AD[userService.deleteLangfuseConfig]
AE[useFetchLangfuseConfig] -->|fetches| AF[userService.getLangfuseConfig]
style A,C,E,G,I,K,M,O,Q,S,U,W,Y,AA,AC,AE fill:#f9f,stroke:#333,stroke-width:1px
style B,D,F,H,J,L,N,P,R,T,V,X,Z,AB,AD,AF fill:#bbf,stroke:#333,stroke-width:1px
Summary
This file serves as a centralized collection of React Query-based hooks facilitating user, tenant, and system-related data operations. It abstracts API calls, manages cache, provides user feedback, and integrates localization, enabling developers to easily implement user settings and system configuration features in the app.