-2

EDIT: I created another react app and started over and it worked

I just started learning React and I was following alone to this tutorial when react gave me an error saying "movie is not defined". So I did some console logging and found out that setMovies(data.Search); is not actually setting the array to the useState.

function App() {
  const [movies, setMovies] = useState([]);

  useEffect(() => {
    searchMovies("superman");
  }, []);

  const searchMovies = async (title) => {
    const response = await fetch(`${API_URL}&s=${title}`);
    const data = await response.json();
    console.log(data.Search);
    setMovies(data.Search);
    console.log(movies);
  };  

  return (
    <div className='app'>
      <h1>MovieLand</h1>
      <div className='search'>
        <input placeholder='Search for movies' value="Superman" onChange={() => { }} />
        <img src={SearchIcon} alt="search" onClick={() => { }} />
      </div>

      {
        movies?.length > 0
          ? (
            <div className='container'>
              {
                movies.map((movie) => {
                  <MovieCard movie={movie} />
                })
              }
            </div>
          ) : (
            <div className='empty'>
              <h2>No movies found</h2>
            </div>
          )
      }
    </div>
  );
}

The console.log(data.Search) grabs the array of movies from the api just fine but when I try console.log(movies) it doesn't show the movies but instead gives me an empty array.

3 Answers3

2

setState work asynchronous so when you console.log your state after setState, your console.log will log your initialState. Try to console.log outside the function.

Nghe Minh
  • 173
  • 6
1

As @NgheMinh mentioned useState is asynchronous and you have to console.log inside a useEffect.

But the actual issue in your code is you have to returned the JSX component from the map function.

<div className='container'>
  {
    movies.map((movie) => {
      return <MovieCard movie={movie} />
    })
  }
</div>
Shakya Peiris
  • 504
  • 5
  • 11
-3

Try this

setMovies(prev=>[...prev, data.Search])
BGOPC
  • 201
  • 9