Proyectos de Subversion LeadersLinked - SPA

Rev

Rev 3514 | Ir a la última revisión | Autoría | Comparar con el anterior | Ultima modificación | Ver Log |

import { useState, useEffect, useCallback } from 'react';

export function useDebouncedSearchParam(paramName, debounceDelay = 500) {
  const getQueryFromUrl = useCallback(() => {
    const params = new URLSearchParams(window.location.search);
    return params.get(paramName);
  }, [paramName]);

  const [inputValue, setInputValue] = useState(() => getQueryFromUrl() || '');
  const [debouncedValue, setDebouncedValue] = useState(() => getQueryFromUrl() || '');

  // Effect to initialize inputValue from URL if it changes externally
  // or on initial load if not already set by useState initializer
  useEffect(() => {
    const queryFromUrl = getQueryFromUrl();
    if (queryFromUrl !== null && queryFromUrl !== inputValue) {
      setInputValue(queryFromUrl);
    }
  }, [getQueryFromUrl, inputValue]);

  // Effect for debouncing inputValue to debouncedValue
  useEffect(() => {
    const handler = setTimeout(() => {
      setDebouncedValue(inputValue);
    }, debounceDelay);

    return () => {
      clearTimeout(handler);
    };
  }, [inputValue, debounceDelay]);

  // Effect for updating URL when debouncedValue changes
  useEffect(() => {
    const params = new URLSearchParams(window.location.search);
    const currentParamValue = params.get(paramName);

    if (debouncedValue) {
      if (currentParamValue !== debouncedValue) {
        params.set(paramName, debouncedValue);
        window.history.replaceState({}, '', `${window.location.pathname}?${params.toString()}`);
      }
    } else {
      if (currentParamValue !== null) {
        params.delete(paramName);
        const newSearch = params.toString();
        window.history.replaceState(
          {},
          '',
          `${window.location.pathname}${newSearch ? '?' : ''}${newSearch}`
        );
      }
    }
  }, [debouncedValue, paramName]);

  return { inputValue, setInputValue, debouncedValue };
}