useTraceQueryParamStateSync.tsx 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. import {useEffect, useRef} from 'react';
  2. import * as qs from 'query-string';
  3. import {browserHistory} from 'sentry/utils/browserHistory';
  4. // Syncs query params with URL state. Only performs a state sync if the query params have changed.
  5. export function useTraceQueryParamStateSync(query: Record<string, string | undefined>) {
  6. const previousQueryRef = useRef<Record<string, string | undefined>>(query);
  7. const syncStateTimeoutRef = useRef<number | null>(null);
  8. useEffect(() => {
  9. const keys = Object.keys(query);
  10. const previousKeys = Object.keys(previousQueryRef.current);
  11. if (
  12. keys.length === previousKeys.length &&
  13. keys.every(key => {
  14. return query[key] === previousQueryRef.current[key];
  15. })
  16. ) {
  17. previousQueryRef.current = query;
  18. return;
  19. }
  20. if (syncStateTimeoutRef.current !== null) {
  21. window.clearTimeout(syncStateTimeoutRef.current);
  22. }
  23. previousQueryRef.current = query;
  24. syncStateTimeoutRef.current = window.setTimeout(() => {
  25. browserHistory.replace({
  26. pathname: location.pathname,
  27. query: {
  28. ...qs.parse(location.search),
  29. ...previousQueryRef.current,
  30. },
  31. });
  32. }, 1000);
  33. }, [query]);
  34. }