Does this only happen when you update the searchTerm or also when you update other filters like for example sortField?
Pagination Page Reset By Changing Filters (Is One Character Behind)
Hi everyone I have this Inertia Index Page which is a data table and some filters like search, sort, daterange ... I have a problem with pagination: When user is in page=5 and searches something like "test" because only there is 1 page results available (or no results at all) there is an empty page in page=5$search=test...
So I tried to reset the page in query string when the filters change and its working fine:
export default function Index({ users, filters }) {
const searchDebounceTimer = useRef(null);
const [searchTerm, setSearchTerm] = useState(filters.search);
const [searchField, setSearchField] = useState(filters.searchField);
const [sortField, setSortField] = useState(filters.sortBy);
const [sortDirField, setSortDirField] = useState(filters.dir);
const [dateRange, setDateRange] = useState([
filters.dateStart,
filters.dateEnd,
]);
const [dateString, setDateString] = useState(filters.date);
const searchUsers = () => {
const queryParams = {
...(searchTerm && { search: searchTerm }),
...(searchField && { searchField: searchField }),
...(sortField && { sortBy: sortField }),
...(sortDirField && { dir: sortDirField }),
...(dateString && { date: dateString }),
};
// Check if any filter other than page has changed
const filtersChanged = Object.keys(filters).some(
(key) => key !== 'page' && filters[key] !== queryParams[key]
);
// Reset page to 1 if any filter has changed
const newPage = filtersChanged ? 1 : filters.page;
if (searchTerm !== null) {
router.get(
'/users',
{
...queryParams,
page: newPage,
},
{
preserveState: true,
replace: true,
}
);
}
};
useEffect(() => {
clearTimeout(searchDebounceTimer.current);
searchDebounceTimer.current = setTimeout(searchUsers, 200);
}, [searchTerm, searchField, sortField, sortDirField, dateString]);
...
...
...
for search I have a problem: Page Reset is one character behind ("test" example) page=5&search=t -> does nothing, i should type second character to make it reset page: page=5&search=te -> page=1&search=te
So search input is one character behind And Other fields should be assigned once before they can do the page reset on change I dont know if its related to them not being defined or something else
I was wondering if its the right strategy or i should figure it out in backend instead of front
I really appreciate your help Regards
@emmatraversy I personally always use ->appends() with a different approach which doesn't require me to reset the page in the front end.
Add this to set which page to use in the pagination, if there's not page in the request use 1 as default.
$page = $request->page ?? 1;
Then with paginate use this
->paginate(10, ['*'], 'page', $page)->appends(['search', 'searchField', 'sortBy', 'dir', 'date']);
Please or to participate in this conversation.