fix: listvirtual last data if has more data request again
This commit is contained in:
parent
1797af7ba9
commit
a6371b64fa
221
README.md
221
README.md
@ -1,16 +1,219 @@
|
||||
# React + Vite
|
||||
# ListVirtual
|
||||
|
||||
This template provides a minimal setup to get React working in Vite with HMR and some ESLint rules.
|
||||
A searchable dropdown component with server-side filtering, infinite scrolling, and support for both single and multiple selection.
|
||||
|
||||
Currently, two official plugins are available:
|
||||
## Features
|
||||
|
||||
- [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react) uses [Oxc](https://oxc.rs)
|
||||
- [@vitejs/plugin-react-swc](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react-swc) uses [SWC](https://swc.rs/)
|
||||
* Server-side search
|
||||
* Infinite scrolling
|
||||
* Single select mode
|
||||
* Multiple select mode
|
||||
* Custom request headers via `ApiProvider`
|
||||
* Default value support
|
||||
* Material UI integration
|
||||
|
||||
## React Compiler
|
||||
---
|
||||
|
||||
The React Compiler is not enabled on this template because of its impact on dev & build performances. To add it, see [this documentation](https://react.dev/learn/react-compiler/installation).
|
||||
## Installation
|
||||
|
||||
## Expanding the ESLint configuration
|
||||
```bash
|
||||
npm install your-library-name
|
||||
```
|
||||
|
||||
If you are developing a production application, we recommend using TypeScript with type-aware lint rules enabled. Check out the [TS template](https://github.com/vitejs/vite/tree/main/packages/create-vite/template-react-ts) for information on how to integrate TypeScript and [`typescript-eslint`](https://typescript-eslint.io) in your project.
|
||||
## Import
|
||||
|
||||
```jsx
|
||||
import { ApiProvider, ListVirtual } from "your-library-name";
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Setup
|
||||
|
||||
Wrap your application or component with `ApiProvider` to provide API headers.
|
||||
|
||||
```jsx
|
||||
<ApiProvider
|
||||
headers={{
|
||||
Authorization: `Bearer ${token}`,
|
||||
}}
|
||||
>
|
||||
<ListVirtual
|
||||
id="company-select"
|
||||
label="Company"
|
||||
name="name"
|
||||
url="/company"
|
||||
/>
|
||||
</ApiProvider>
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Single Selection
|
||||
|
||||
```jsx
|
||||
const [company, setCompany] = useState(null);
|
||||
|
||||
<ListVirtual
|
||||
id="company-select"
|
||||
label="Company"
|
||||
name="name"
|
||||
url="/company"
|
||||
getData={(row) => {
|
||||
setCompany(row);
|
||||
}}
|
||||
/>
|
||||
```
|
||||
|
||||
### Selected Value
|
||||
|
||||
```js
|
||||
{
|
||||
id: 123,
|
||||
name: "My Company"
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Multiple Selection
|
||||
|
||||
```jsx
|
||||
const [companies, setCompanies] = useState([]);
|
||||
|
||||
<ListVirtual
|
||||
id="company-select"
|
||||
label="Company"
|
||||
name="name"
|
||||
url="/company"
|
||||
multiple
|
||||
getData={(rows) => {
|
||||
setCompanies(rows);
|
||||
}}
|
||||
/>
|
||||
```
|
||||
|
||||
### Selected Value
|
||||
|
||||
```js
|
||||
[
|
||||
{
|
||||
id: 1,
|
||||
name: "Company A"
|
||||
},
|
||||
{
|
||||
id: 2,
|
||||
name: "Company B"
|
||||
}
|
||||
]
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Using Default Value
|
||||
|
||||
### Single Selection
|
||||
|
||||
```jsx
|
||||
<ListVirtual
|
||||
id="company-select"
|
||||
label="Company"
|
||||
name="name"
|
||||
url="/company"
|
||||
defaultValue={{
|
||||
id: 123,
|
||||
name: "My Company"
|
||||
}}
|
||||
/>
|
||||
```
|
||||
|
||||
### Multiple Selection
|
||||
|
||||
```jsx
|
||||
<ListVirtual
|
||||
id="company-select"
|
||||
label="Company"
|
||||
name="name"
|
||||
url="/company"
|
||||
multiple
|
||||
defaultValue={[
|
||||
{
|
||||
id: 1,
|
||||
name: "Company A"
|
||||
},
|
||||
{
|
||||
id: 2,
|
||||
name: "Company B"
|
||||
}
|
||||
]}
|
||||
/>
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Props
|
||||
|
||||
| Prop | Type | Default | Description |
|
||||
| ------------ | -------------- | --------- | ----------------------------------------- |
|
||||
| id | string | - | Unique component identifier |
|
||||
| label | string | - | TextField label |
|
||||
| name | string | - | Property name used for display |
|
||||
| url | string | - | API endpoint used to fetch data |
|
||||
| getData | function | undefined | Callback triggered when selection changes |
|
||||
| defaultValue | object | array | undefined | Initial selected value |
|
||||
| multiple | boolean | false | Enable multiple selection mode |
|
||||
| disabled | boolean | false | Disable the component |
|
||||
| required | boolean | false | Mark field as required |
|
||||
| error | boolean | false | Error state |
|
||||
| helperText | string | undefined | Helper text displayed below the field |
|
||||
| size | string | "medium" | TextField size (`small` or `medium`) |
|
||||
| lengthData | number | 100 | Number of records fetched per request |
|
||||
| filter | array | [] | Additional API filters |
|
||||
| isApiGo | boolean | false | Use Go API request mode |
|
||||
|
||||
---
|
||||
|
||||
## Custom Filters
|
||||
|
||||
```jsx
|
||||
<ListVirtual
|
||||
id="company-select"
|
||||
label="Company"
|
||||
name="name"
|
||||
url="/company"
|
||||
filter={[
|
||||
{
|
||||
name: "status",
|
||||
value: 1,
|
||||
logic_operator: "="
|
||||
}
|
||||
]}
|
||||
/>
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## API Response Format
|
||||
|
||||
The component expects the API response to have the following structure:
|
||||
|
||||
```json
|
||||
{
|
||||
"data": [
|
||||
{
|
||||
"id": 1,
|
||||
"name": "Company A"
|
||||
}
|
||||
],
|
||||
"totalRecord": 100
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Notes
|
||||
|
||||
* The property specified in the `name` prop is used as the displayed label.
|
||||
* Infinite scrolling automatically loads additional records when the user reaches the bottom of the list.
|
||||
* In multiple mode, the `getData` callback returns an array of selected objects.
|
||||
* In single mode, the `getData` callback returns a single selected object.
|
||||
|
||||
7834
dist/index.js
vendored
7834
dist/index.js
vendored
File diff suppressed because it is too large
Load Diff
21
src/App.jsx
21
src/App.jsx
@ -1,9 +1,12 @@
|
||||
import ListVirtual from "./components/ListVirtual";
|
||||
import { ApiProvider } from "./components/ApiContext";
|
||||
import { API_TOKEN } from "./config/constants";
|
||||
import { useState } from "react";
|
||||
|
||||
const Testing = () => {
|
||||
const token = API_TOKEN;
|
||||
const [selectedVehicle, setSelectedVehicle] = useState(null);
|
||||
|
||||
return (
|
||||
<div style={{ padding: 8, marginTop: 12 }}>
|
||||
<ApiProvider
|
||||
@ -11,13 +14,29 @@ const Testing = () => {
|
||||
Authorization: `Bearer ${token}`,
|
||||
}}
|
||||
>
|
||||
<ListVirtual
|
||||
{/* <ListVirtual
|
||||
id="company-select"
|
||||
label="Company"
|
||||
name="name"
|
||||
url="/company"
|
||||
defaultValue={"442"}
|
||||
size="small"
|
||||
multiple
|
||||
/> */}
|
||||
<ListVirtual
|
||||
label="License Plate"
|
||||
name="license_plate"
|
||||
url="/vehicle"
|
||||
defaultValue={selectedVehicle}
|
||||
getData={(data) => {
|
||||
if (data) {
|
||||
setSelectedVehicle(data.id);
|
||||
}
|
||||
}}
|
||||
size="small"
|
||||
filter={[
|
||||
{name:"company_id",value: "740","logic_operator":"=","operator":"AND"}
|
||||
]}
|
||||
/>
|
||||
</ApiProvider>
|
||||
</div>
|
||||
|
||||
@ -14,7 +14,8 @@ const createClient = (baseURL, withBaseFormat = false) => {
|
||||
formatApiResponse({
|
||||
status: response.status,
|
||||
data: response.data,
|
||||
message: response.data?.message ?? response.statusText
|
||||
message: response.data?.message ?? response.statusText,
|
||||
totalRecord: response.totalRecord ?? 0
|
||||
}),
|
||||
(error) => Promise.resolve(formatApiResponse(error))
|
||||
);
|
||||
|
||||
@ -29,7 +29,7 @@ const request = async ({
|
||||
...axiosConfig
|
||||
});
|
||||
|
||||
return formatApiResponse(response);
|
||||
return response
|
||||
} catch (error) {
|
||||
return formatApiResponse(error);
|
||||
}
|
||||
|
||||
@ -11,7 +11,8 @@ import {
|
||||
ListItemText,
|
||||
Typography,
|
||||
InputAdornment,
|
||||
IconButton
|
||||
IconButton,
|
||||
Checkbox
|
||||
} from "@mui/material";
|
||||
import ClearIcon from "@mui/icons-material/Clear";
|
||||
import FilterTableBuilder from "../utils/filterTableBuilder";
|
||||
@ -34,6 +35,7 @@ export default function ListVirtual({
|
||||
helperText,
|
||||
filter,
|
||||
isApiGo = false,
|
||||
multiple
|
||||
}) {
|
||||
const headersRequest = useApiHeaders();
|
||||
const [open, setOpen] = useState(false);
|
||||
@ -79,6 +81,8 @@ export default function ListVirtual({
|
||||
isApiGo,
|
||||
);
|
||||
const incomingData = res.data || [];
|
||||
|
||||
console.log("res", res)
|
||||
|
||||
setRows(prev => isAppend ? [...prev, ...incomingData] : incomingData);
|
||||
setTotalRecord(res.totalRecord || 0);
|
||||
@ -92,12 +96,24 @@ export default function ListVirtual({
|
||||
|
||||
const handleScroll = (e) => {
|
||||
const { scrollTop, scrollHeight, clientHeight } = e.currentTarget;
|
||||
|
||||
|
||||
console.log({
|
||||
scrollTop,
|
||||
scrollHeight,
|
||||
clientHeight,
|
||||
rows: rows.length,
|
||||
totalRecord,
|
||||
loading,
|
||||
});
|
||||
|
||||
const isAtBottom = scrollHeight - scrollTop <= clientHeight + 20;
|
||||
|
||||
|
||||
if (isAtBottom && !loading && rows.length < totalRecord) {
|
||||
const nextOffset = offset + lengthData;
|
||||
fetchData(search, nextOffset, true);
|
||||
|
||||
console.log("LOAD MORE", nextOffset);
|
||||
|
||||
fetchData(search, nextOffset, true);
|
||||
}
|
||||
};
|
||||
|
||||
@ -149,27 +165,67 @@ export default function ListVirtual({
|
||||
useEffect(() => {
|
||||
if (!defaultValue) return;
|
||||
|
||||
if (typeof defaultValue === "object") {
|
||||
setSelected(defaultValue);
|
||||
if (multiple) {
|
||||
if (Array.isArray(defaultValue)) {
|
||||
setSelected(defaultValue);
|
||||
} else {
|
||||
setSelected([defaultValue]);
|
||||
}
|
||||
} else {
|
||||
fetchById(defaultValue);
|
||||
if (Array.isArray(defaultValue)) {
|
||||
setSelected(defaultValue[0] || null);
|
||||
} else {
|
||||
setSelected(defaultValue);
|
||||
}
|
||||
}
|
||||
}, [defaultValue]);
|
||||
}, [defaultValue, multiple]);
|
||||
|
||||
const handleSelect = (row) => {
|
||||
setSelected(row);
|
||||
setOpen(false);
|
||||
setSearch("");
|
||||
getData && getData(row);
|
||||
if (!multiple) {
|
||||
setSelected(row);
|
||||
setOpen(false);
|
||||
setSearch("");
|
||||
getData?.(row);
|
||||
return;
|
||||
}
|
||||
|
||||
setSelected((prev) => {
|
||||
const current = Array.isArray(prev) ? prev : [];
|
||||
|
||||
const exists = current.some((x) => x.id === row.id);
|
||||
|
||||
const result = exists
|
||||
? current.filter((x) => x.id !== row.id)
|
||||
: [...current, row];
|
||||
|
||||
getData?.(result);
|
||||
|
||||
return result;
|
||||
});
|
||||
};
|
||||
|
||||
const handleClear = () => {
|
||||
setSelected(null);
|
||||
setSelected(multiple ? [] : null);
|
||||
setSearch("");
|
||||
setRows([]);
|
||||
getData && getData(null);
|
||||
|
||||
getData?.(multiple ? [] : null);
|
||||
};
|
||||
|
||||
const displayValue = multiple
|
||||
? (selected || [])
|
||||
.map((x) => x[name]?.trim())
|
||||
.filter(Boolean)
|
||||
.join(", ")
|
||||
: selected?.[name] || "";
|
||||
|
||||
const isSelected = (row) => {
|
||||
if (!multiple) {
|
||||
return selected?.id === row.id;
|
||||
}
|
||||
|
||||
return (selected || []).some((x) => x.id === row.id);
|
||||
};
|
||||
const displayValue = selected ? selected[name] : value || "";
|
||||
|
||||
return (
|
||||
<>
|
||||
@ -216,7 +272,20 @@ export default function ListVirtual({
|
||||
<DialogTitle sx={{ fontSize: 14 }}>Search {label}</DialogTitle>
|
||||
<DialogContent
|
||||
onScroll={handleScroll}
|
||||
sx={{ height: 400, overflowY: "auto", py: 0 }}
|
||||
sx={{
|
||||
'& .MuiTypography-root': {
|
||||
fontSize: 14,
|
||||
},
|
||||
'& .MuiInputBase-input': {
|
||||
fontSize: 14,
|
||||
},
|
||||
'& .MuiInputLabel-root': {
|
||||
fontSize: 14,
|
||||
},
|
||||
'& .MuiButton-root': {
|
||||
fontSize: 14,
|
||||
},
|
||||
}}
|
||||
>
|
||||
<TextField
|
||||
fullWidth
|
||||
@ -232,17 +301,35 @@ export default function ListVirtual({
|
||||
/>
|
||||
|
||||
<List disablePadding>
|
||||
{rows.map((row, i) => (
|
||||
<ListItemButton key={`${row.id}-${i}`} onClick={() => handleSelect(row)}>
|
||||
<ListItemText primary={row[name]} slotProps={{ primary: { fontSize: 14 } }} />
|
||||
</ListItemButton>
|
||||
))}
|
||||
|
||||
{loading && (
|
||||
<Typography variant="caption" sx={{ display: 'block', textAlign: 'center', p: 1 }}>
|
||||
Loading more...
|
||||
</Typography>
|
||||
)}
|
||||
<>
|
||||
{multiple && (
|
||||
<ListItemButton
|
||||
onClick={() => console.log("")}
|
||||
sx={{ fontSize: 14 }}
|
||||
>
|
||||
Select All
|
||||
</ListItemButton>
|
||||
)}
|
||||
|
||||
{rows.map((row, i) => (
|
||||
<ListItemButton
|
||||
key={`${row.id}-${i}`}
|
||||
onClick={() => handleSelect(row)}
|
||||
>
|
||||
{multiple && (
|
||||
<Checkbox checked={isSelected(row)} />
|
||||
)}
|
||||
|
||||
<ListItemText primary={row[name]} />
|
||||
</ListItemButton>
|
||||
))}
|
||||
|
||||
{loading && (
|
||||
<Typography variant="caption" sx={{ display: 'block', textAlign: 'center', p: 1 }}>
|
||||
Loading more...
|
||||
</Typography>
|
||||
)}
|
||||
</>
|
||||
</List>
|
||||
|
||||
{!loading && rows.length === 0 && (
|
||||
|
||||
@ -1,7 +1,8 @@
|
||||
export const formatApiResponse = (responseOrError) => {
|
||||
if (responseOrError?.status) {
|
||||
const { status, data, message } = responseOrError;
|
||||
|
||||
console.log("status", responseOrError.status)
|
||||
|
||||
if (status >= 200 && status < 300) {
|
||||
return {
|
||||
code: data.code ?? status,
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user