skip to Main Content
import { useState, useEffect } from "react";
import MovieCard from "./MovieCard";

const PopularMovies = () => {
  const [movies, setMovies] = useState([]);
  const [loading, setLoading] = useState(false);
  const [page, setPage] = useState(1);
  const bearerToken = process.env.MY_BEARER_TOKEN;

  const fetchMovies = async () => {
    const options = {
      method: "GET",
      headers: {
        accept: "application/json",
        Authorization: "Bearer " + bearerToken,
      },
    };
    setLoading(true);
    try {
      const res = await fetch(
        "https://api.themoviedb.org/3/movie/popular?language=en-US&page=" +
          page,
        options
      );
      const data = await res.json();
      console.log(data);
      setPage((prevPage) => prevPage + 1);
      setMovies((prevMovies) => [...prevMovies, ...data.results]);
    } catch (error) {
      console.error(error);
    }
    setLoading(false);
  };

  useEffect(() => {
    fetchMovies();
  }, []);

  useEffect(() => {
    window.addEventListener("scroll", handleScroll);
    return () => {
      window.removeEventListener("scroll", handleScroll);
    };
  }, []);

  const handleScroll = () => {
    const { scrollTop, clientHeight, scrollHeight } = document.documentElement;
    if (scrollTop + clientHeight >= scrollHeight - 5 && !loading) {
      fetchMovies();
    }
  };
  console.log(page);

  return (
    <div className="flex flex-wrap mt-10 gap-6 justify-center items-center">
      {movies.map((movie) => (
        <MovieCard key={movie.id} movie={movie} />
      ))}
    </div>
  );
};

export default PopularMovies;

I want to fetch new movies data by updating the value of page from 1
to 2 and so on whenever user reach at the end of page. Everything
working fine, page value is updating correctly but my URL still taking
value 1 and fetching data for same page 1.
please explain me in detail about what could be wrong over here?
am I updating state correctly or not?

2

Answers


  1. read urlSeachParamas docs for setting your url
    https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams%5Benter link description here]1

    Login or Signup to reply.
  2. When you’re updating state in React, especially in asynchronous operations like fetching data, it’s crucial to remember that state updates are not immediate. They are scheduled to happen in the future, so referencing a state variable right after updating it might give you its old value, not the new one.

    In your case, you’re updating the page state and immediately using it to fetch data, which might be causing the issue. Instead, consider calculating the next page number first, use that for fetching, and then update your state with this new value.

    import { useState, useEffect } from "react"; 
    import MovieCard from "./MovieCard";
    
    const PopularMovies = () => {
    const [movies, setMovies] = useState([]);
    const [loading, setLoading] = useState(false);
    const [page, setPage] = useState(1);
    const bearerToken = process.env.MY_BEARER_TOKEN;
    
     const fetchMovies = async () => {
     const nextPage = page + 1; // Calculate the next page number
     const options = {
       method: "GET",
       headers: {
         accept: "application/json",
         Authorization: "Bearer " + bearerToken,
        },
      };
      setLoading(true);
      try {
        const res = await fetch(
          `https://api.themoviedb.org/3/movie/popular?language=en-US&page= {nextPage}`,
         options
         );
         const data = await res.json();
         console.log(data);
         setPage(nextPage); // Update the page state with the new value
         setMovies((prevMovies) => [...prevMovies, ...data.results]);
        } catch (error) {
         console.error(error);
        }
        setLoading(false);
       };
    
       useEffect(() => {
        fetchMovies();
       }, []);
    
       useEffect(() => {
         const handleScroll = () => {
         const { scrollTop, clientHeight, scrollHeight } = document.documentElement;
         if (scrollTop + clientHeight >= scrollHeight - 5 && !loading) {
          fetchMovies();
         }
       };
    
        window.addEventListener("scroll", handleScroll);
        return () => {
        window.removeEventListener("scroll", handleScroll);
        };
        }, [loading]); // Adding loading to the dependency array
    
       console.log(page);
    
       return (
        <div className="flex flex-wrap mt-10 gap-6 justify-center items-center">
        {movies.map((movie) => (
          <MovieCard key={movie.id} movie={movie} />
         ))}
         </div>
        );
        };
    
        export default PopularMovies;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search