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,
};
};
✅ 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.
Top comments (1)
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.