Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

130
Vistas
Getting API with useEffect, inside a handle change function

I'm using the YTS API and I need to change the link for the call, I have to use ?query_term= and add the text that the user is typing, for autocomplete. I'm using mantine components for the autocomplete. I tried putting the call inside the handlechange function, but this is not possible.

const [movieNames, setMovieNames] = useState([])

const onChangeHandler = (text) => {
    useEffect(() => {
        const loadMovieNames = async () => {
            const response = await axios.get('https://yts.mx/api/v2/list_movies.json?query_term='+text);
            let arrayOfMoviesNames = [];

            response.data.data.movies.forEach(i => {
                arrayOfMoviesNames.push(i.title)
            });
            setMovieNames(arrayOfMoviesNames)
        }
        loadMovieNames()
    }, [])
}

.

<Autocomplete
         placeholder="Search Movie"
         limit={8}
         data={movieNames}
         onChange={e => onChangeHandler(e.target.value)}
/>
about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

You MUST use hooks in the execution context of Function Component, you used the useEffect inside a function not in the execution context of Function Component.

const YourComponent = () => {
  const [movieNames, setMovieNames] = useState([]);
  
  const loadMovieNames = async (text) => {
    const response = await axios.get(
      'https://yts.mx/api/v2/list_movies.json?query_term=' + text
    );
    let arrayOfMoviesNames = [];
  
    response.data.data.movies.forEach((i) => {
      arrayOfMoviesNames.push(i.title);
    });
    setMovieNames(arrayOfMoviesNames);
  };


  return (
    <Autocomplete
      placeholder="Search Movie"
      limit={8}
      data={movieNames}
      onChange={(value) => loadMovieNames(value)}
    />
  );
};
about 4 years ago · Juan Pablo Isaza Denunciar

0

It is also possible without useEffect, so without making it so complicated by using useEffect and onChangeHandler both, only use onChangeHandler function to update the movieNames and it will automatically update the DOM texts (I mean where ever you use)...

import React, { useState } from "react";

function MoviesPage(props) {
  const [ movieNames, setMovieNames ] = useState([]);
  const [ searchValue, setSearchValue ] = useState("");

  const onChangeHandler = async (text) => {
    const response = await axios.get(
      'https://yts.mx/api/v2/list_movies.json?query_term=' + text
    );

    let arrayOfMoviesNames = [];

    response.data.data.movies.forEach(i => {
      arrayOfMoviesNames.push(i.title)
    });
    
    setMovieNames(arrayOfMoviesNames);
  }

  return (
    <div>
      <Autocomplete
        placeholder="Search Movie"
        limit={8}
        data={movieNames}
        onChange={(e) => onChangeHandler(e.target.value)}
      />
    </div>
  );
}

export default MoviesPage;

...and just to clarify, you can use useEffect in case of API if you want to initialize the page with the API data. You can use this hook if you don't have any onChange handlers. Another way you can approach is you can update a state hook (like searchData) on the change of the Search Bar, and lastly add the the searchData variable to the useEffect dependency array:

useEffect(() => {
  // use the searchData variable to populate or update the page
  // ...
},
[
  searchData, // <-- talking about this line
]);

So, this was my solution. Hope this helps you mate!

about 4 years ago · Juan Pablo Isaza Denunciar

0

useEffect is a hook, which executes on state change, So keep the useEffect funtion outside the onChangeHandler and add a new state for 'query param' and setQueryState(text) inside the onChangeHandler, and put the state param as dependency in useEffect, So whenever this state gets changed this will call the use effect function automatically.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda