Home > Software engineering >  I want to get Movie list(API) when I submit
I want to get Movie list(API) when I submit

Time:08-10

I want to get Movie list(API) when I submit, so I made my API link by using Template literals like this ▼

  const getMovies = async () => {
    const json = await (
      await fetch(
        `https://yts.mx/api/v2/list_movies.json?minimum_rating=8&page=${Math.round(Math.random()*100)}&query_term=${movieName}&sort_by=year`
      )
    ).json();
    setMovies(json.data.movies);
    setLoading(false);
  };

then, I filled 'movieName' into the array of useEffect. because I want to Refetch the API everytime the 'movieName' Changed.

but! it dosen't work:(

what is the problem?

▼ code i wrote

import { useEffect, useRef, useState } from "react";
import Movie from "../components/Movie";

function Home(){
  const [loading, setLoading] = useState(true);
  const [movies, setMovies] = useState([]);
  const [movieSearch, setMovieSearch] = useState('');
  const [movieName, setMovieName] = useState('');

  const getMovies = async () => {
    const json = await (
      await fetch(
        `https://yts.mx/api/v2/list_movies.json?minimum_rating=8&page=${Math.round(Math.random()*100)}&query_term=${movieName}&sort_by=year`
      )
    ).json();
    setMovies(json.data.movies);
    setLoading(false);
  };

  const onChange = (event) =>{
    setMovieSearch(event.target.value)
  }

  const onSubmit = (event)=>{
    event.preventDefault();
    setMovieName(movieSearch)
  }

  useEffect(() => {
    getMovies();
  }, [movieName]);

  return (
    <>
    <h4>Search</h4>
    <form onSubmit={onSubmit}>
      <input
      onChange={onChange}
      type="text"
      value={movieSearch}
      placeholder="..."
      ></input>
    </form>
      {loading ? (
        <h3>Loading</h3>
      ) : (
        <div>
          {movies.map((item) => (
            <Movie
              key={item.id}
              id={item.id}
              title={item.title}
              year={item.year}
              medium_cover_image={item.medium_cover_image}
              rating={item.rating}
              runtime={item.runtime}
              genres={item.genres}
              summary={item.summary}
            />
          ))}
        </div>
      )}
    </>
  );
}

CodePudding user response:

why not trying to move getMovies() that is inside the useEffect to the onSubmit() function right after you set the movie name?

CodePudding user response:

Because you don't update the answerName state on the onChange event of the search input

const onChange = (event) =>{ const value = event.target.value setMovieSearch(value) setMovieName(value) }

  • Related