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}
/>
One solution is use the shallow routing, but I can't find any documentation of useRouter (from next/navigation) using the shallow equals true.
You can check this out
import { usePathname, useSearchParams, useRouter } from "next/navigation";
import { useState, useEffect } from "react";
export default function Home() {
const [searchQuery, setSearchQuery] = useState({
name: "",
// you can add more keys to this
});
const searchParams = useSearchParams();
const pathname = usePathname();
const router = useRouter();
const handleInputChange = (event) => {
const { name, value } = event.target;
const updatedQuery = { ...searchQuery, [name]: value };
setSearchQuery(updatedQuery);
updateSearchQuery(updatedQuery);
};
const updateSearchQuery = (updatedQuery) => {
const params = new URLSearchParams(searchParams);
Object.keys(updatedQuery).forEach((key) => {
if (updatedQuery[key]) {
params.set(key, updatedQuery[key]);
} else {
params.delete(key);
}
});
params.set('page', '1');
const queryString = params.toString();
const updatedPath = queryString ? `${pathname}?${queryString}` : pathname;
router.push(updatedPath);
};
return (
<main>
<div>
<input
type="text"
className="form-control"
placeholder="Name of the user"
id="name"
name="name"
value={searchQuery.name}
onChange={handleInputChange}
/>
</div>
</main>
);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With