Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Emokores's avatar

Page rerendering during pagination - Inertia/ReactJS

I have a table that displays a list from the database. It uses live search to filter data from the backend. However, when I try to use the pagination (Laravel pagination) the component instead rerenders back to page 1 whenever I go to page 2 or some other page.

// This is the code in the controller
$search = $request->query('q');

'clients' => Client::query()->when($search, fn($query) => $query->where(...))
                  ->paginate()->withQueryString()->through(fn ($client) => [
                           'name' => $client->name,
                           'email' => $client->email,
                           'mobile_number' => $client->mobile_number
                  ]),
'filters' => $request->only(['filters'])
const { filters, clients } = usePage().props
const [query, setQuery] = useState(filters.q)

useEffect(() => {
      return router.get(route(route().current()), {q: query}, {
           preserveState: true,
           replace: true
      })
}, [query])

// render the list:
clients.map()

This doesn't seem to work as expected, but the live search works perfectly fine. I have a problem going to the next page. The server returns http://localhost:8005/clients when the page rerenders instead of http://localhost:8005/clients?page=2 when I click on the next page. I access page 2 when I type the URL manually.

0 likes
1 reply
LaryAI's avatar
Level 58

The issue is that the withQueryString() method is not working as expected. To fix this, you can manually add the query string to the URL in the useEffect hook. Here's an updated code snippet:

const { filters, clients } = usePage().props
const [query, setQuery] = useState(filters.q)

useEffect(() => {
  const queryString = new URLSearchParams({ q: query }).toString()
  const url = `${window.location.pathname}?${queryString}`
  return router.get(url, {}, { preserveState: true, replace: true })
}, [query])

// render the list:
clients.map()

This code creates a new URLSearchParams object with the q parameter set to the current search query. It then converts this object to a string and appends it to the current URL using window.location.pathname. This ensures that the correct URL is used when navigating between pages.

Note that you may need to adjust the URL construction depending on your specific routing setup.

Please or to participate in this conversation.