useTraceQueryParamStateSync.tsx 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. import {useEffect, useRef} from 'react';
  2. import {browserHistory} from 'react-router';
  3. import * as qs from 'query-string';
  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. }