12345678910111213141516171819202122232425262728293031323334353637383940 |
- import {useEffect, useRef} from 'react';
- import * as qs from 'query-string';
- import {browserHistory} from 'sentry/utils/browserHistory';
- // Syncs query params with URL state. Only performs a state sync if the query params have changed.
- export function useTraceQueryParamStateSync(query: Record<string, string | undefined>) {
- const previousQueryRef = useRef<Record<string, string | undefined>>(query);
- const syncStateTimeoutRef = useRef<number | null>(null);
- useEffect(() => {
- const keys = Object.keys(query);
- const previousKeys = Object.keys(previousQueryRef.current);
- if (
- keys.length === previousKeys.length &&
- keys.every(key => {
- return query[key] === previousQueryRef.current[key];
- })
- ) {
- previousQueryRef.current = query;
- return;
- }
- if (syncStateTimeoutRef.current !== null) {
- window.clearTimeout(syncStateTimeoutRef.current);
- }
- previousQueryRef.current = query;
- syncStateTimeoutRef.current = window.setTimeout(() => {
- browserHistory.replace({
- pathname: location.pathname,
- query: {
- ...qs.parse(location.search),
- ...previousQueryRef.current,
- },
- });
- }, 1000);
- }, [query]);
- }
|