DEV Community

JAKER HOSSAIN
JAKER HOSSAIN

Posted on • Edited on

2

Managing URL Query Parameters with useCustomParams

import { useRouter, useSearchParams } from "next/navigation";

export const useCustomParams = ({ routeName = "" }: { routeName: string }) => {
  const router = useRouter();
  const searchParams = useSearchParams();

  const setQueryParam = (key: string, value: string) => {
    const params = new URLSearchParams(searchParams);
    params.set(key, value);
    router.replace(`/${routeName}?${params.toString()}`);
  };

  const removeQueryParam = (key: string, valueToRemove?: string) => {
    const params = new URLSearchParams(searchParams);
    if (valueToRemove) {
      const values = params.get(key)?.split(",") || [];
      const updatedValues = values.filter((val) => val !== valueToRemove);
      if (updatedValues.length) {
        params.set(key, updatedValues.join(","));
      } else {
        params.delete(key);
      }
    } else {
      params.delete(key);
    }
    const queryString = params.toString();
    router.replace(
      queryString ? `/${routeName}?${queryString}` : `/${routeName}`
    );
  };

  const clearAllQueryParams = () => {
    router.replace(`/${routeName}`);
  };

  return {
    setQueryParam,
    removeQueryParam,
    clearAllQueryParams,
  };
};

Enter fullscreen mode Exit fullscreen mode

✅ setQueryParam:
This method adds or updates a query parameter in the URL, giving you the flexibility to modify search parameters on the fly. It’s perfect for dynamically applying filters or search settings based on user input.

✅ removeQueryParam:
This function removes a specific query parameter by its key, allowing you to fine-tune the URL by removing unnecessary filters or parameters while keeping the rest of the URL intact. It’s ideal for clearing specific filters without affecting others.
Note: Modified removeQueryParam to delete the specific value from the key and that works superbly.

✅ clearAllQueryParams:
This method clears all query parameters, resetting the URL to its base route. It’s particularly useful for scenarios where you want to return to a clean state, such as resetting search results or filters.

Postgres on Neon - Get the Free Plan

No credit card required. The database you love, on a serverless platform designed to help you build faster.

Get Postgres on Neon

Top comments (1)

Collapse
 
jackfd120 profile image
JAKER HOSSAIN

Here is a little modified version of removeQueryParam:

If the expected key has multiple values like brandName=Puma, Walton, Singer, etc., removing a specific value adds valueToRemove the property and works superbly.

  const removeQueryParam = (key: string, valueToRemove?: string) => {
    const params = new URLSearchParams(searchParams);
    if (valueToRemove) {
      const values = params.get(key)?.split(",") || [];
      const updatedValues = values.filter((val) => val !== valueToRemove);
      if (updatedValues.length) {
        params.set(key, updatedValues.join(","));
      } else {
        params.delete(key);
      }
    } else {
      params.delete(key);
    }
    const queryString = params.toString();
    router.replace(
      queryString ? `/${routeName}?${queryString}` : `/${routeName}`
    );
  };
Enter fullscreen mode Exit fullscreen mode

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay