Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

77
Visualizações
useEffect debounce search technique

i'm trying to implement search functionality but i don't want to call the api every time i type something . here is the code:

const [term, setTerm] = useState("");
const [result, setResult] = useState([]);

useEffect(() => {
  const search = async () => {
    const respond = await axios.get("https://en.wikipedia.org/w/api.php", {
      params: {
        action: "query",
        list: "search",
        origin: "*",
        format: "json",
        srsearch: term,
      },
    });
    setResult(respond.data.query.search);
  };

  if (!result.length) {
    if (term) {
      search();
    }
  }
}, [term, result.length]);
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

you can use the setTimeout() function and clearTimeout in the cleanup function and the useRef hook to get the previous state to call the API only once :

  const [result, setResult] = useState([]);
  const termUseRef = useRef(); 

  useEffect(() => {
    termUseRef.current = term
 
  })

  const prevTerm = termUseRef.current;


  useEffect(() => {
    const search = async () => {
      const respond = await axios.get('https://en.wikipedia.org/w/api.php', {
        params: {
          action: 'query',
          list: 'search',
          origin: '*',
          format: 'json',
          srsearch: term,
        },
      });
      setResult(respond.data.query.search);
    };

    if (!result.length) {
      if (term) {
        search();
      }

    } else if(term !== prevTerm) {
      const debounceSearch = setTimeout(() => {
        if (term) {
          search();
        }
      }, 1200);

      return () => {
        clearTimeout(debounceSearch);
      };
    }
  }, [term, result.length, prevTerm]);
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda