#Pagination Using Query Params

1 messages · Page 1 of 1 (latest)

jaunty heath
#

My backend only provides start and limit as the payload for the pagination. I wanted to put the state in query params so when you refresh the page, it would still retain the values.The pagination on the frontend is through pages.
Something like http://localhost:3000/products?currentPage=2&itemsPerPage=5.

How should I do it?

zinc smelt
#

In the loader for the procuts route you can read the currentPage and itemsPerPage from the request. Something like :
export const loader = async ({ params, request }: DataFunctionArgs) => { const url = new URL(request.url); const currentPage = Number(url.searchParams.get('currentPage')) const itemsPerPage = Number(url.searchParams.get('itemsPerPage'))
If i understand the backend api correctly, you can set
const start = (currentPage - 1) * itemsPerPage; const limit = itemsPerPage;
Then you can use them in a fetch request againts the api
const data = await fetch('api-url' + '?start=' + start + '&limit=' + limit)
and then return the data from you loader.
Either just
return data
or
const dataObj = await data.json(); return json(dataObj);