Search code examples
javascriptreactjsjsonnext.jsinfinite-scroll

Infinite scrolling in ReactJS from scratch


I should create an infinite scroll in reactJs having a JSON with data in it. Could you help me?

I would like to do it from scratch and not with some library

{data?.map((conto) => {

  return (
    <Suspense key={conto._uid} fallback={<p>Loading...</p>}>
      <Conto blok={conto} data={data} ITEuro={ITEuro} deposit={deposit} handleToggleFavourite={handleToggleFavourite} isFavourited={isFavourited} depositQuantity={depositQuantity} />
    </Suspense>
  )

})}

I load the JSON like this for now, but I would like a maximum number of ids to be loaded until we reach the bottom of the page and more are loaded


Solution

  • I managed to solve it this way

    export default function App() {
      const [limiteData, setLimiteData] = useState([]);
      const [page, setPage] = useState(1);
      const [isLoading, setIsLoading] = useState(false);
    
      const fetchData = useCallback(() => {
         setIsLoading(true);
    
         // Simula un ritardo di caricamento per mostrare l'indicatore di caricamento
         setTimeout(() => {
           const newData = data.slice((page - 1) * 5, page * 5); // Carica 10 elementi per pagina
           setLimiteData((prevData) => [...prevData, ...newData]);
           setPage((prevPage) => prevPage + 1);
           setIsLoading(false);
         }, 1000);
      }, [page]);
    
      useEffect(() => {
        fetchData();
      }, [fetchData]);
    
      return (
        <div className="App">
          {limiteData.map((blok) => {
            return (
              <div key={blok._uid}>
                <h1>{blok.name}</h1>
              </div>
            );
          })}
          <Suspense fallback={<p>Loading...</p>}>
            {isLoading && <p>Loading...</p>}
           </Suspense>
        </div>
      );
    }