DEV Community

San
San

Posted on

Use of useDebounce while searching data. Send data on value change using useRouter hook next

1. Step 1 to get value and send via routes

const [searchValue, setSearchValue] = useState("");
  const [searchQuery] = useDebounce(searchValue, 600);

  useEffect(() => {
    if (!searchQuery) {
      router.push("/");
    } else {
      router.push(`/search?q=${searchQuery}`);
    }
  }, [searchQuery, router]);
Enter fullscreen mode Exit fullscreen mode

2. On the search page get data using useSeachParams

const searchParams = useSearchParams();
const searchTextValue: any = searchParams.get("q");
Enter fullscreen mode Exit fullscreen mode

3. Add filter logic

const filterSearchProduct = liveProducts?.filter((elm: any) => {
    return elm.title?.toLowerCase()?.includes(searchTextValue?.toLowerCase());
  });

Then render data where you want to show it!


Enter fullscreen mode Exit fullscreen mode

Top comments (0)