I
I
ivan_ivanov_ivanych2022-02-12 15:44:33
JavaScript
ivan_ivanov_ivanych, 2022-02-12 15:44:33

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>
    }

But if you make conditions, then first ...Loading is rendered, and then the main content. And in this case, uploading photos during tracking does not work
Code:
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 question

Ask a Question

731 491 924 answers to any question