React lazy loading data with Spring boot

773 views Asked by At

My solution is based on a front app React , redux and material-u and a backend Springboot app.

I have a Rest API that fetch a big number of records from the database. This creates a delay on the UI and I would like to prevent this.

Table component:

export default function Export(props) {
  return (
   <div>
  <MaterialTable
    title={<Typography variant="h6">{}</Typography>}
    data={props.data}
    options={{
      pageSize: 50,
      pageSizeOptions: [50, 100, 150],
      search: true,
      sorting: false,
      headerStyle: {
        fontWeight: "bold",
        padding: "4px",
      },
    }}
  ></MaterialTable>
</div>
 );
}


export const getExportByLastModifiedDate = (lastModifiedDate) => {
 return async (dispatch) => {
   dispatch({ type: EXPORT_BY_LASTMODIFEDDATE_START });
   await axios({
      method: "get",
      url: "/api/export?lastModifiedDate=" + lastModifiedDate,
  })
  .then(function(response) {
    dispatch({
      type: EXPORT_BY_LASTMODIFEDDATE_SUCCESS,
      payload: response.data,
    });
  })
  .catch(function(error) {
    dispatch({ type: EXPORT_BY_LASTMODIFEDDATE_ERROR, payload: error });
  });
 };
};

Backend API:

@GetMapping("/export")
public ResponseEntity<List<ExportDto>> getExportByLastModifiedDate(@RequestParam(value = "lastModifiedDate", required = true) String lastModifiedDate) {
    
    Optional<List<ExportDto>> optional = Optional.ofNullable(service.getExportByLastModifiedDate(lastModifiedDate));
    return optional.map(response -> ResponseEntity.ok().body(response)).orElse(new ResponseEntity<>(HttpStatus.NOT_FOUND));
}

What I am trying to do is to get the first 1000 records and to render them to the UI while in the backend the process will continue.

How can I do that ?

Thank you

1

There are 1 answers

0
Shawrup On BEST ANSWER

One possible solution may be adding pagination support in your query and backend rest api. For example, first you call your backend with page=0&pageSize=1000, this will return you first 1000 records, after this records are loaded, you will then call the backend with page=1&pageSize=1000, this will return the next 1000 records.

Spring boot has good pagination support for pagination if you are using spring data jpa. If you are using native query then, most databases has syntax supporting this kind of pagination and you need to modify your query for pagination.