I’m attempting to dynamically update query parameters based on user input using the onChange event. However, I’m encountering an issue where, upon entering text, the query parameters are updated first, and only after a brief delay does the input value get updated. My goal is to achieve real-time synchronization between the input value and the query parameters, but the current implementation isn’t achieving that.
Below is the relevant JavaScript code implemented in a Next.js 14 environment (App Router), utilizing the useSearchParams, usePathname, and useRouter hooks. I already put the ‘use client’ on top of the component.
const searchParams = useSearchParams();
const pathname = usePathname();
const router = useRouter();
const name = searchParams.get('name') || '';
const handleFilter = (e) => {
const { name: key, value } = e.target;
const params = new URLSearchParams(searchParams);
params.set(key, value);
params.set('page', 1);
router.push(`${pathname}?${params.toString()}`);
};
<input
type="text"
className="form-control"
placeholder="Name of the user"
id="name"
name="name"
value={name}
onChange={handleFilter}
/>
2
Answers
Make the input controlled by keeping the value in a state will keep it reactive.
You can check this out