Search code examples
javascriptreactjsapimantine

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)}
/>

Solution

  • 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)}
        />
      );
    };