skip to Main Content

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


  1. Make the input controlled by keeping the value in a state will keep it reactive.

    Login or Signup to reply.
  2. You can check this out

    import Link from "next/link";
    import { useRouter } from 'next/router';
    import { useEffect, useState } from 'react';
    
    export default function IndexPage() {
      const router = useRouter();
      const [searchQuery, setSearchQuery] = useState('');
      useEffect(() => {
        const { query } = router;
        if (query && query.search) {
          setSearchQuery(query.search);
        }
      }, [router]);
    
      const handleInputChange = (event) => {
        const value = event.target.value;
        setSearchQuery(value);
    
        router.replace({
          pathname: router.pathname,
          query: { ...router.query, search: value },
        });
      };
      return (
        <div>
          <input
            type="text"
            value={searchQuery}
            onChange={handleInputChange}
            placeholder="Search..."
          />
        </div>
      );
    }
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search