All files / src/hooks searchParams.ts

84% Statements 21/25
84.61% Branches 11/13
100% Functions 4/4
88.23% Lines 15/17

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    893362x     893362x 893362x 503x 503x 503x     1254692x 1435357x 1254692x     17x 17x     1x 1x 1x     23x    
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;
    });
  };
}