File size: 1,057 Bytes
2bd3674
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
32
33
34
35
36
37
38
39
40
41
export default function setURLParam<T>(
  paramName: string,
  value: T,
  // If there's no defaultValue specified then we always set the URL param explicitly
  defaultValue?: T,
): void {
  const urlParams = new URLSearchParams(window.location.search);
  if (defaultValue != null && value === defaultValue) {
    urlParams.delete(paramName);
  } else {
    let stringValue: string;

    switch (typeof value) {
      case 'string':
        stringValue = value;
        break;
      case 'boolean':
        stringValue = value ? '1' : '0';
        break;
      default:
        throw new Error(`Unsupported URL param type: ${typeof value}`);
    }

    if (urlParams.has(paramName)) {
      urlParams.set(paramName, stringValue);
    } else {
      urlParams.append(paramName, stringValue);
    }
  }

  const paramStringWithoutQuestionMark = urlParams.toString();

  window.history.replaceState(
    null,
    '',
    `${window.location.pathname}${
      paramStringWithoutQuestionMark.length > 0 ? '?' : ''
    }${paramStringWithoutQuestionMark}`,
  );
}