Answer the question
In order to leave comments, you need to log in
Why doesn't the IntersectionObserver fire when the page is first rendered?
I am writing an application that downloads photos from the server and renders them on the page. Implemented endless uploading of photos. Everything works if the page renders the main content immediately, without these conditions:
else if (error && !load) {
return <div className="error">{error}</div>
} else {
return <div className="loading">...Loading</div>
}
import React, { useCallback, useEffect , useState, useRef} from "react";
import unsplashUser from "../../unsplash/unsplash.js";
import { toJson } from "unsplash-js";
function PhotoList(props) {
const [page, setPage] = useState(1);
const [images, setImages] = useState([]);
const [load, setLoader] = useState(false);
const [error, setError] = useState(false)
const loader = useRef(null);
//колбэк для IntersectionObserver
const handleObserver = useCallback((entries) => {
const target = entries[0];
if (target.isIntersecting) {
setPage((prev) => prev + 1);
}
}, []);
//Подключаю отслеживание
useEffect(() => {
const option = {
root: null,
rootMargin: '50px',
threshold: 0.5
};
const observer = new IntersectionObserver(handleObserver, option);
if (loader.current) {
observer.observe(loader.current);
}
}, [handleObserver])
//Запросы с сервера при загрузки страницы
useEffect(() => {
try {
unsplashUser.photos.listPhotos(page, 15, 'latest')
.then(toJson)
.then(data => {
setImages((prevState) => {
return [...new Set([...prevState, ...data])]
});
setLoader(true)
})
} catch (error) {
console.log('error ' + error);
setError(true)
}
}, [page])
if(load) {
//Здесь основной рендеринг страницы, я это все пропустил оставил только loader в конце, к которому привязывается IntersectionObserver
return (
<main className="fixed-container">
....
<div className="loader" ref={loader}></div>
</main>
)
} else if (error && !load) {
return <div className="error">{error}</div>
} else {
return <div className="loading">...Loading</div>
}
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question