Search bar problem (useRouter)
Unanswered
Cuban Crocodile posted this in #help-forum
Cuban CrocodileOP
I have the following code. Generally when I type sth the defaultValue for Input changes but when I click some links that redirect me to "/" or somewhere else then the defaultValue does not change (I mean input, when i console.log variable then I see correct value but it does not impact input's value). Why it work that way? Does "replace" from useRouter reload the whole page? Ultimately, what should I do to reset input's value when I'm not within '/search' route? Btw <Search> is rendered by layout.tsx
'use client'
import { usePathname, useRouter, useSearchParams } from "next/navigation"
import { Input } from "./ui/input"
import { ChangeEvent } from "react"
export default function Search()
{
const searchParams = useSearchParams()
const pathname = usePathname();
const {replace} = useRouter()
const defaultValue = pathname === "/search" ? searchParams.get('query') || "" : ""
const handleSearch = (e: ChangeEvent<HTMLInputElement>) => {
const params = new URLSearchParams(searchParams)
params.set('query', e.currentTarget.value)
console.log(params.toString(), e.currentTarget.value)
replace(`/search?${params.toString()}`)
}
return <Input onChange={handleSearch} placeholder="Search..." defaultValue={defaultValue} />
}