I'm trying to make new requests whenever user reach the bottom with the following;
useEffect(() => {
const scrolling_function = () => {
if((window.innerHeight + window.scrollY) >= document.body.offsetHeight-10){
window.removeEventListener('scroll',scrolling_function)
getMoviesFromApi()
}
}
window.addEventListener('scroll', scrolling_function);
}, [])
But the state objects that I defined, such as:
const[selectedGenres, setSelectedGenres] = useState(new Set())
All becomes undefined in the inside of my useEffect hook, and thus my getMoviesFromApi() method does not work properly.
My question is, is that expected behavior? If so, how could I overcome it?
The getmoviesfromapi method:
const getMoviesFromApi = async () => {
setLoading(true)
let init, end;
if(initialYear>endYear) {
init = endYear
end = initialYear
} else {
init = initialYear
end = endYear
}
let res =await fetchMovies(init, end)
setLoading(false)
setMovies(res.results)
}
The fetchMovies method:
const fetchMovies = async (startYear, endYear) => {
let res;
res = [];
let genreQuery = "";
let serviceQuery = "";
for (let it = selectedGenres.values(), val= null; val=it.next().value; ) {
genreQuery += "&genre=" + val;
}
for (let it = selectedServices.values(), val= null; val=it.next().value; ) {
serviceQuery += "&service=" + val;
}
let countryQuery = "?country="+country;
let yearQuery = "&year_min="+ startYear +"&year_max=" + endYear;
let typeQuery = "&type=" + (isMovie ? "movie" : "series");
let url = api_url + countryQuery + serviceQuery + typeQuery +"&order_by=year" + yearQuery
+ genreQuery + "&page=1&desc=true&language=en&output_language=en"
await fetch(url, {
"method": "GET",
}).then(response => {
res= response.json()
})
.catch(err => {
console.error(err);
});
return res;
};
Via Active questions tagged javascript - Stack Overflow https://ift.tt/2FdjaAW
Comments
Post a Comment