useTraceQueryParamStateSync.tsx 1.1 KB

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