Live search with pagination in React.js

1.4k views Asked by At

I want to search in all pages, but my code only search in the current page.
For example I'm in the page 2/5 when I type the name of a tourist who is present in this page it shows me the data,
but when I type a tourist which is in the page 4/5 it not show me anything.
I'm using Laravel in backend.
Here's the backend code :

$tourists = Tourist::where('hotel_id', $request->hotel_id)->orderBy('created_at', 'DESC')->paginate(10);
return $toursits;

Frontend code :

this.state = {
      activePage: 1,
      tourists: []
}
async componentDidMount() {
    await this.getTourists();
  }
async getTourists() {
    let response = await callApi('tourists/paginate', { page: this.state.activePage, hotel_id: this.context.hotel_id[0] });
    this.setState({ tourists: response.data, perPage: response.meta.per_page, total: response.meta.total, lastPage: response.meta.last_page });
  }

Render method:

{this.state.tourists
            .filter(x => new RegExp (this.state.first_name, 'i').test(x.first_name)
.map((tourist, i) =>
              <tr>
                <td>{tourist.first_name}</td>
              </tr>)}
1

There are 1 answers

0
Julien Verneaut On

You are getting a paginated list of results from the backend but you are implementing the search functionality on the frontend.

When you first go to your page, you get the first 10 results from your server. At the time, your React application as no idea that there are more results to be parsed and can only "see" the 10 paginated results your are sending from your server. By filtering these results you will not be able to get any other result which was not sent by the server in the first place.

You have 2 solutions:

  1. Implement the pagination client-side,
  2. Implement the search functionality server-side

Given that you already implemented pagination on the server I assume that you have a lot of results and that sending all of them at once would not be practical.

This leaves us with option n°2. Adding to your code example, you could do something like:

$tourists = Tourist::where('hotel_id', $request->hotel_id)
                   // Add this to filter results by first_name
                   ->where('first_name', 'like', "%{$request->first_name}%"))
                   ->orderBy('created_at', 'DESC')->paginate(10);

return $tourists;