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?
read
urlSeachParamasdocs for setting your url