All files / src/hooks searchParams.ts

100% Statements 14/14
100% Branches 2/2
100% Functions 6/6
100% Lines 14/14

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29          916240x 916240x 2984x 2984x 2984x 2984x     916240x 916240x       16x   16x 1x 1x 1x 1x        
import { useSearchParams } from "react-router-dom";
 
export function useSearchParam(param: string, defaultValue?: string) {
  // Helper function for if you just need to update one search param.
  // If you need to update more than one search param, use useSearchParams.
  const [searchParams, setSearchParams] = useSearchParams();
  const setParam = (value) => {
    setSearchParams((searchParams) => {
      const newSearchParams = new URLSearchParams(searchParams);
      newSearchParams.set(param, value);
      return newSearchParams;
    });
  };
  const value = searchParams.get(param) || defaultValue;
  return [value, setParam] as const;
}
 
export function useDeleteSearchParam() {
  const [_, setSearchParams] = useSearchParams();
 
  return (key: string) => {
    setSearchParams((prev) => {
      const newSearchParams = new URLSearchParams(prev);
      newSearchParams.delete(key);
      return newSearchParams;
    });
  };
}