All files / platform/app/src/hooks useSearchParams.ts

91.66% Statements 11/12
100% Branches 4/4
100% Functions 1/1
91.66% Lines 11/12

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 30 31                    272x 272x 272x 272x   272x     272x 136x     136x   136x 140x     136x    
import { useLocation } from 'react-router';
 
/**
 * It returns a URLSearchParams of the query parameters in the URL, where the keys are
 * either lowercase or maintain their case based on the lowerCaseKeys parameter.
 * This will automatically include the hash parameters as preferred parameters
 * @param {lowerCaseKeys:boolean} true to return lower case keys; false (default) to maintain casing;
 * @returns {URLSearchParams}
 */
export default function useSearchParams(options = { lowerCaseKeys: false }) {
  const { lowerCaseKeys } = options;
  const location = useLocation();
  const searchParams = new URLSearchParams(location.search);
  const hashParams = new URLSearchParams(location.hash?.substring(1) || '');
 
  for (const [key, value] of hashParams) {
    searchParams.set(key, value);
  }
  if (!lowerCaseKeys) {
    return searchParams;
  }
 
  const lowerCaseSearchParams = new URLSearchParams();
 
  for (const [key, value] of searchParams) {
    lowerCaseSearchParams.set(key.toLowerCase(), value);
  }
 
  return lowerCaseSearchParams;
}