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)
|
* Server-side search
|
||||||
- [@vitejs/plugin-react-swc](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react-swc) uses [SWC](https://swc.rs/)
|
* 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 ListVirtual from "./components/ListVirtual";
|
||||||
import { ApiProvider } from "./components/ApiContext";
|
import { ApiProvider } from "./components/ApiContext";
|
||||||
import { API_TOKEN } from "./config/constants";
|
import { API_TOKEN } from "./config/constants";
|
||||||
|
import { useState } from "react";
|
||||||
|
|
||||||
const Testing = () => {
|
const Testing = () => {
|
||||||
const token = API_TOKEN;
|
const token = API_TOKEN;
|
||||||
|
const [selectedVehicle, setSelectedVehicle] = useState(null);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div style={{ padding: 8, marginTop: 12 }}>
|
<div style={{ padding: 8, marginTop: 12 }}>
|
||||||
<ApiProvider
|
<ApiProvider
|
||||||
@ -11,13 +14,29 @@ const Testing = () => {
|
|||||||
Authorization: `Bearer ${token}`,
|
Authorization: `Bearer ${token}`,
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<ListVirtual
|
{/* <ListVirtual
|
||||||
id="company-select"
|
id="company-select"
|
||||||
label="Company"
|
label="Company"
|
||||||
name="name"
|
name="name"
|
||||||
url="/company"
|
url="/company"
|
||||||
defaultValue={"442"}
|
defaultValue={"442"}
|
||||||
size="small"
|
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>
|
</ApiProvider>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@ -14,7 +14,8 @@ const createClient = (baseURL, withBaseFormat = false) => {
|
|||||||
formatApiResponse({
|
formatApiResponse({
|
||||||
status: response.status,
|
status: response.status,
|
||||||
data: response.data,
|
data: response.data,
|
||||||
message: response.data?.message ?? response.statusText
|
message: response.data?.message ?? response.statusText,
|
||||||
|
totalRecord: response.totalRecord ?? 0
|
||||||
}),
|
}),
|
||||||
(error) => Promise.resolve(formatApiResponse(error))
|
(error) => Promise.resolve(formatApiResponse(error))
|
||||||
);
|
);
|
||||||
|
|||||||
@ -29,7 +29,7 @@ const request = async ({
|
|||||||
...axiosConfig
|
...axiosConfig
|
||||||
});
|
});
|
||||||
|
|
||||||
return formatApiResponse(response);
|
return response
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
return formatApiResponse(error);
|
return formatApiResponse(error);
|
||||||
}
|
}
|
||||||
|
|||||||
@ -11,7 +11,8 @@ import {
|
|||||||
ListItemText,
|
ListItemText,
|
||||||
Typography,
|
Typography,
|
||||||
InputAdornment,
|
InputAdornment,
|
||||||
IconButton
|
IconButton,
|
||||||
|
Checkbox
|
||||||
} from "@mui/material";
|
} from "@mui/material";
|
||||||
import ClearIcon from "@mui/icons-material/Clear";
|
import ClearIcon from "@mui/icons-material/Clear";
|
||||||
import FilterTableBuilder from "../utils/filterTableBuilder";
|
import FilterTableBuilder from "../utils/filterTableBuilder";
|
||||||
@ -34,6 +35,7 @@ export default function ListVirtual({
|
|||||||
helperText,
|
helperText,
|
||||||
filter,
|
filter,
|
||||||
isApiGo = false,
|
isApiGo = false,
|
||||||
|
multiple
|
||||||
}) {
|
}) {
|
||||||
const headersRequest = useApiHeaders();
|
const headersRequest = useApiHeaders();
|
||||||
const [open, setOpen] = useState(false);
|
const [open, setOpen] = useState(false);
|
||||||
@ -80,6 +82,8 @@ export default function ListVirtual({
|
|||||||
);
|
);
|
||||||
const incomingData = res.data || [];
|
const incomingData = res.data || [];
|
||||||
|
|
||||||
|
console.log("res", res)
|
||||||
|
|
||||||
setRows(prev => isAppend ? [...prev, ...incomingData] : incomingData);
|
setRows(prev => isAppend ? [...prev, ...incomingData] : incomingData);
|
||||||
setTotalRecord(res.totalRecord || 0);
|
setTotalRecord(res.totalRecord || 0);
|
||||||
setOffset(currentOffset);
|
setOffset(currentOffset);
|
||||||
@ -93,10 +97,22 @@ export default function ListVirtual({
|
|||||||
const handleScroll = (e) => {
|
const handleScroll = (e) => {
|
||||||
const { scrollTop, scrollHeight, clientHeight } = e.currentTarget;
|
const { scrollTop, scrollHeight, clientHeight } = e.currentTarget;
|
||||||
|
|
||||||
|
console.log({
|
||||||
|
scrollTop,
|
||||||
|
scrollHeight,
|
||||||
|
clientHeight,
|
||||||
|
rows: rows.length,
|
||||||
|
totalRecord,
|
||||||
|
loading,
|
||||||
|
});
|
||||||
|
|
||||||
const isAtBottom = scrollHeight - scrollTop <= clientHeight + 20;
|
const isAtBottom = scrollHeight - scrollTop <= clientHeight + 20;
|
||||||
|
|
||||||
if (isAtBottom && !loading && rows.length < totalRecord) {
|
if (isAtBottom && !loading && rows.length < totalRecord) {
|
||||||
const nextOffset = offset + lengthData;
|
const nextOffset = offset + lengthData;
|
||||||
|
|
||||||
|
console.log("LOAD MORE", nextOffset);
|
||||||
|
|
||||||
fetchData(search, nextOffset, true);
|
fetchData(search, nextOffset, true);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
@ -149,27 +165,67 @@ export default function ListVirtual({
|
|||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!defaultValue) return;
|
if (!defaultValue) return;
|
||||||
|
|
||||||
if (typeof defaultValue === "object") {
|
if (multiple) {
|
||||||
|
if (Array.isArray(defaultValue)) {
|
||||||
setSelected(defaultValue);
|
setSelected(defaultValue);
|
||||||
} else {
|
} else {
|
||||||
fetchById(defaultValue);
|
setSelected([defaultValue]);
|
||||||
}
|
}
|
||||||
}, [defaultValue]);
|
} else {
|
||||||
|
if (Array.isArray(defaultValue)) {
|
||||||
|
setSelected(defaultValue[0] || null);
|
||||||
|
} else {
|
||||||
|
setSelected(defaultValue);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}, [defaultValue, multiple]);
|
||||||
|
|
||||||
const handleSelect = (row) => {
|
const handleSelect = (row) => {
|
||||||
|
if (!multiple) {
|
||||||
setSelected(row);
|
setSelected(row);
|
||||||
setOpen(false);
|
setOpen(false);
|
||||||
setSearch("");
|
setSearch("");
|
||||||
getData && getData(row);
|
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 = () => {
|
const handleClear = () => {
|
||||||
setSelected(null);
|
setSelected(multiple ? [] : null);
|
||||||
setSearch("");
|
setSearch("");
|
||||||
setRows([]);
|
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 (
|
return (
|
||||||
<>
|
<>
|
||||||
@ -216,7 +272,20 @@ export default function ListVirtual({
|
|||||||
<DialogTitle sx={{ fontSize: 14 }}>Search {label}</DialogTitle>
|
<DialogTitle sx={{ fontSize: 14 }}>Search {label}</DialogTitle>
|
||||||
<DialogContent
|
<DialogContent
|
||||||
onScroll={handleScroll}
|
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
|
<TextField
|
||||||
fullWidth
|
fullWidth
|
||||||
@ -232,9 +301,26 @@ export default function ListVirtual({
|
|||||||
/>
|
/>
|
||||||
|
|
||||||
<List disablePadding>
|
<List disablePadding>
|
||||||
|
<>
|
||||||
|
{multiple && (
|
||||||
|
<ListItemButton
|
||||||
|
onClick={() => console.log("")}
|
||||||
|
sx={{ fontSize: 14 }}
|
||||||
|
>
|
||||||
|
Select All
|
||||||
|
</ListItemButton>
|
||||||
|
)}
|
||||||
|
|
||||||
{rows.map((row, i) => (
|
{rows.map((row, i) => (
|
||||||
<ListItemButton key={`${row.id}-${i}`} onClick={() => handleSelect(row)}>
|
<ListItemButton
|
||||||
<ListItemText primary={row[name]} slotProps={{ primary: { fontSize: 14 } }} />
|
key={`${row.id}-${i}`}
|
||||||
|
onClick={() => handleSelect(row)}
|
||||||
|
>
|
||||||
|
{multiple && (
|
||||||
|
<Checkbox checked={isSelected(row)} />
|
||||||
|
)}
|
||||||
|
|
||||||
|
<ListItemText primary={row[name]} />
|
||||||
</ListItemButton>
|
</ListItemButton>
|
||||||
))}
|
))}
|
||||||
|
|
||||||
@ -243,6 +329,7 @@ export default function ListVirtual({
|
|||||||
Loading more...
|
Loading more...
|
||||||
</Typography>
|
</Typography>
|
||||||
)}
|
)}
|
||||||
|
</>
|
||||||
</List>
|
</List>
|
||||||
|
|
||||||
{!loading && rows.length === 0 && (
|
{!loading && rows.length === 0 && (
|
||||||
|
|||||||
@ -1,6 +1,7 @@
|
|||||||
export const formatApiResponse = (responseOrError) => {
|
export const formatApiResponse = (responseOrError) => {
|
||||||
if (responseOrError?.status) {
|
if (responseOrError?.status) {
|
||||||
const { status, data, message } = responseOrError;
|
const { status, data, message } = responseOrError;
|
||||||
|
console.log("status", responseOrError.status)
|
||||||
|
|
||||||
if (status >= 200 && status < 300) {
|
if (status >= 200 && status < 300) {
|
||||||
return {
|
return {
|
||||||
|
|||||||
Loading…
x
Reference in New Issue
Block a user