I have a custom data table using primeReact. I have a global search. I implemented the global search as follows
handleGlobalSearch = () => {
const { globalSearch } = this.state;
const { data } = this.props;
if (globalSearch) {
const filteredData = data.filter((row) =>
Object.values(row).some((value) =>
(value as any).toString().toLowerCase().includes(globalSearch.toLowerCase())
)
);
this.setState({
dataToDisplay: filteredData,
currentPage: 1,
});
} else {
this.setState({
dataToDisplay: data,
currentPage: 1,
});
}};
It will only search for the data table records. But I want it to be a callback function so that it can search the whole data base records of the API that I am calling for getting the data in the table. The API’s will differ from table to table as this custom data table will be used with different API’s and different data. How can I achieve this. Can someone help me with this!
Thanks in advance!
2
Answers
To implement a global search that can retrieve data from different APIs depending on the specific table, you can create a callback function that takes a search query as a parameter and fetches data from the corresponding API. You can pass this callback function as a prop to your custom data table component and use it when the global search is initiated.
Here’s a basic structure for achieving this:
Create a callback function for fetching data based on the search query. This function will vary depending on the API for each table.
Pass the callback function as a prop to your custom data table component.
In your custom data table component, call the callback function when the global search is initiated, and pass the search query as a parameter.
Update the table with the new data obtained from the API.
Here’s an example of how to structure your code:
In this example, DataTableContainer is the parent component that defines the callback function fetchDataFromAPI, which fetches data from the API based on the search query. This function is then passed to the CustomDataTable component as a prop. When the global search is initiated, the callback function is called, and the table is updated with the new data. The specifics of the API call should be adapted to your use case.
@January to use PrimeReact in a callback mode where it is looking at your Database live you need to use "lazy" mode like in this example: https://primereact.org/datatable/#lazy_load
I have a full working demo which use PostGresDB on the backend and shows you how to wire it up to REST services to make your PrimeReact Datatable fully lazy: https://github.com/melloware/quarkus-monorepo