hooks.ts
Overview
The hooks.ts file contains custom React hooks designed to handle core logic related to fetching, searching, pagination, and saving "flows" in a React application. These hooks integrate with external services and utilities such as API services (flowService), React Query (useInfiniteQuery), debounce utilities (useDebounce), and React Router (useNavigate). The hooks encapsulate state management logic and side effects for flow-related features, promoting reusable and maintainable UI components.
Detailed Documentation
1. useFetchDataOnMount
Purpose
useFetchDataOnMount is a custom hook that:
Manages a search input with debouncing.
Fetches paginated (infinite) flow data from a backend API filtered by the search term.
Supports loading states, error handling, and fetching additional pages.
Functionality
Uses a debounced search string to reduce redundant API calls.
Fetches flow list data in pages of fixed size (30 items per page).
Determines if more pages are available based on total count returned by the API.
Exposes relevant states and handlers to components for UI rendering and interaction.
Parameters
This hook takes no parameters.
Returns
An object with the following properties:
Property | Type | Description |
|---|---|---|
|
| The paginated flow list data fetched from the API. |
|
| True while data is being fetched initially. |
|
| Error object if the fetch operation fails. |
|
| Function to fetch the next page of data. |
|
| Indicates if more pages are available for fetching. |
|
| Whether any fetch operation is currently in progress. |
|
| True when the next page is being fetched. |
|
| Status string from React Query (e.g., 'loading', 'error', 'success'). |
| Handler to update the search input value. | |
|
| Current value of the search input. |
Usage Example
import React from 'react';
import { useFetchDataOnMount } from './hooks';
const FlowList = () => {
const {
data,
loading,
error,
fetchNextPage,
hasNextPage,
handleInputChange,
searchString,
} = useFetchDataOnMount();
return (
<div>
<input type="text" value={searchString} onChange={handleInputChange} placeholder="Search flows..." />
{loading && <p>Loading...</p>}
{error && <p>Error loading flows.</p>}
<ul>
{data?.pages?.flat().map(flow => (
<li key={flow.id}>{flow.title}</li>
))}
</ul>
{hasNextPage && <button onClick={() => fetchNextPage()}>Load More</button>}
</div>
);
};
Implementation Details
Uses
useHandleSearchChangecustom hook to manage the input state.Applies
useDebounceto delay the search input processing by 500ms.Uses
useInfiniteQueryfrom React Query to handle infinite scrolling pagination.The
queryFncallsflowService.listCanvasTeamwith pagination and search keywords.The
getNextPageParamfunction calculates if more pages should be fetched based on the total number of items returned.
2. useSaveFlow
Purpose
useSaveFlow is a custom hook that handles the flow creation or saving process including:
Managing the visibility state of the flow setting modal.
Setting flow data via an API call.
Navigating to the newly created or updated flow page.
Providing loading state and template list data for UI.
Functionality
Retrieves modal state management functions (
showModal,hideModal,visible) fromuseSetModalState.Uses
useSetFlowto perform the save operation and track loading status.Fetches flow templates from
useFetchFlowTemplatesto support template-based flow creation.Provides a callback
onFlowOkto create/save the flow and handle navigation upon success.
Parameters
This hook takes no parameters.
Returns
An object containing:
Property | Type | Description |
|---|---|---|
|
| Loading state while saving the flow. |
|
| Initial name for the flow (empty string here). |
|
| Callback to save flow data using title and selected template. |
|
| Whether the flow setting modal is visible. |
|
| Function to hide the flow setting modal. |
|
| List of available flow templates. |
|
| Function to show the flow setting modal. |
Usage Example
import React, { useState } from 'react';
import { useSaveFlow } from './hooks';
const FlowCreationModal = () => {
const {
flowSettingLoading,
onFlowOk,
flowSettingVisible,
hideFlowSettingModal,
templateList,
showFlowSettingModal,
} = useSaveFlow();
const [title, setTitle] = useState('');
const [selectedTemplateId, setSelectedTemplateId] = useState(templateList[0]?.id || '');
if (!flowSettingVisible) {
return <button onClick={showFlowSettingModal}>Create New Flow</button>;
}
return (
<div className="modal">
<input value={title} onChange={e => setTitle(e.target.value)} placeholder="Flow Title" />
<select value={selectedTemplateId} onChange={e => setSelectedTemplateId(e.target.value)}>
{templateList.map(t => (
<option key={t.id} value={t.id}>{t.name}</option>
))}
</select>
<button onClick={() => onFlowOk(title, selectedTemplateId)} disabled={flowSettingLoading}>
{flowSettingLoading ? 'Saving...' : 'Save'}
</button>
<button onClick={hideFlowSettingModal}>Cancel</button>
</div>
);
};
Implementation Details
onFlowOkuses thesetFlowfunction to save the flow with the selected template's DSL and avatar.After a successful save (indicated by
ret.code === 0), the modal is hidden and the user navigated to the new flow's page.Uses React Router's
useNavigateto change route programmatically.Uses
useCallbackfor memoization of the save handler to avoid unnecessary re-renders.
Important Implementation Notes
Debouncing: The search functionality uses
useDebouncefromahooksto optimize API calls by waiting 500ms after the user stops typing before triggering a search.Infinite Pagination: React Query's
useInfiniteQuerymanages the fetching of paginated data seamlessly with built-in support for fetching additional pages and caching.Modal State Management: Modal visibility and controls are abstracted via
useSetModalStatehook, likely a shared hook managing modal dialogs in the application.Flow Templates: The flow creation process supports templates fetched through
useFetchFlowTemplates, allowing users to start from predefined flow structures.
Interaction with Other Parts of the System
Hooks from other modules:
useSetModalState(fromcommon-hooks): Manages modal dialog visibility and control.useFetchFlowTemplatesanduseSetFlow(fromflow-hooks): Manage flow templates and flow saving operations respectively.useHandleSearchChange(fromlogic-hooks): Manages the search input state and change handler.
Services:
flowService.listCanvasTeam: API call to fetch the list of team flows with pagination and search keywords.
Routing:
Uses
useNavigatefromumifor client-side navigation after flow creation.
Third-party libraries:
@tanstack/react-queryfor data fetching and caching.ahooksfor debounce functionality.React's
useCallbackfor memoization.
This file acts as a bridge between UI components and backend services, encapsulating complex logic related to flow data fetching, searching, pagination, and creation in reusable hooks.
Mermaid Diagram
flowchart TD
subgraph useFetchDataOnMount
A1[useHandleSearchChange] --> A2[searchString]
A3[useDebounce] --> A4[debouncedSearchString]
A2 --> A3
A4 --> A5[useInfiniteQuery]
A5 -->|calls| flowService.listCanvasTeam
A5 -->|returns| data & status
A6[returns data, loading, error, etc.]
end
subgraph useSaveFlow
B1[useSetModalState] --> B2[modal controls]
B3[useSetFlow] --> B4[setFlow, loading]
B5[useNavigate] --> B6[navigation]
B7[useFetchFlowTemplates] --> B8[template list]
B2 & B4 & B6 & B8 --> B9[onFlowOk callback]
B9 -->|calls| setFlow
B9 -->|on success| hideFlowSettingModal & navigate
B10[returns flowSettingLoading, handlers, templateList, modal visibility]
end
Summary
The hooks.ts file provides two main hooks:
useFetchDataOnMountfor debounced search and infinite pagination of flows.useSaveFlowfor managing flow creation with modal controls, template selection, saving, and navigation.
These hooks abstract away complex data fetching and state management logic, using React Query, debounce, and React Router internally, facilitating clean and maintainable UI components to create, list, and search flows efficiently.