In this tutorial, we will implement a grid data provider to enable lazy loading in a React data grid using the Vaadin Grid component. Lazy loading helps us efficiently load large datasets by fetching only the required data as the user scrolls through the grid.
This tutorial is based on Hilla 2.0 and React. You can find the full source code of the example on GitHub.
Backend: Create a PageResponse and a method for fetching data by page
First, in the backend Endpoint, we need to create a record PageResponse
that will return a list of Person
objects and the total count of items in the database. In the PersonEndpoint
class, add the following code:
public record PageResponse(List<Person> items, long totalCount) {
}
Next, create a new method called getPeople
that takes in two parameters: the page number and the page size. This method will fetch the data one page at a time using the Spring Data PageRequest
object:
public PageResponse getPeople(int page, int pageSize) {
var res = personRepository.findAll(PageRequest.of(page, pageSize));
return new PageResponse(res.getContent(), res.getTotalElements());
}
Frontend: Implement the Grid dataProvider
Now that we have our backend ready, we can create a data provider in our React component. The data provider is a function that fetches data for the Vaadin Grid as the user scrolls through it.
First, create an asynchronous function called dataProvider
that takes in two parameters: GridDataProviderParams<Person>
and GridDataProviderCallback<Person>
:
async function dataProvider(
params: GridDataProviderParams<Person>,
callback: GridDataProviderCallback<Person>
) {
// Implementation goes here
}
Inside the dataProvider function, call the PersonEndpoint.getPeople
method using the parameters page
and pageSize
. Once the data is fetched, pass it to the callback:
const res = await PersonEndpoint.getPeople(params.page, params.pageSize);
callback(res.items, res.totalCount);
Finally, in your React component, set the dataProvider
property of the Grid
component to the newly created dataProvider
function:
<Grid className="flex-grow" dataProvider="{dataProvider}">
<GridColumn path="firstName" />
<GridColumn path="lastName" />
<GridColumn path="email" autoWidth />
<GridColumn path="phone" />
<GridColumn path="dateOfBirth" />
</Grid>
That's it! Your data grid now lazy loads items on scroll, fetching only the required data as needed. Check out and run the completed application source code to try it out in action.