
We can implement infinite scrolling using the IntersectionObserver API given by browser.
To implement we can simply follow these steps :-
CustomHook.jsx
import axios from "axios"; import { useEffect, useState } from "react"; import { API_URL } from "../common/constants"; export const useAuthorList = (limit, page) => { const [isLoading, setIsLoading] = useState(false); const [authorList, setAuthorList] = useState([]); const [error, setError] = useState(""); const [hasMore, setHasMore] = useState(true); useEffect(() => { setIsLoading(true); setTimeout(() => { axios({ method: "GET", url: API_URL, params: { limit: limit, page: page }, }) .then((res) => { setAuthorList(res.data.data); setHasMore(res.data.data.length === limit); setIsLoading(false); }) .catch((e) => setError(e)); }, 500); }, [limit, page]); return [isLoading, authorList, error, hasMore]; };
App.jsx
import React, { useCallback, useRef, useState } from "react"; import { useAuthorList } from "./hooks/useAuthorList"; import { AuthorQuotes } from "./components/AuthorQuotes"; const App = () => { const [limit, setLimit] = useState(10); const [page, setPage] = useState(1); const [isLoading, authorList, error, hasMore] = useAuthorList(limit, page); const observer = useRef(null); const infiniteReference = useCallback( (element) => { if (isLoading) return; if (observer.current) { observer.current.disconnect(); } observer.current = new IntersectionObserver((entries) => { if (entries[0].isIntersecting && hasMore) { setLimit((prev) => prev + 10); } }); if (element) { observer.current.observe(element); } }, [isLoading, hasMore] ); return ( {authorList.length > 0 && authorList.map((authorQuotes, index) => { if (index + 1 === authorList.length) { return ( ); } return ; })} {isLoading && <>Loading...>} ); }; export default App;
constants.js
export const API_URL = "https://api.javascripttutorial.net/v1/quotes/"
The above is the detailed content of Master Infinite Scrolling in Easy Steps. For more information, please follow other related articles on the PHP Chinese website!
HP notebook sound card driver
How many years do you have to pay for medical insurance to enjoy lifelong medical insurance?
How to use panel control
How to remove other people's TikTok watermarks from TikTok videos
What system is Honor?
How to buy and sell Bitcoin legally
What file is mid format?
How to use insert statement in mysql