Toggle

Integrating Frontend and Backend

This example demonstrates how to integrate the EndlessFlow package with a React frontend and set up a Node.js backend for infinite scroll functionality. Please note that this is a basic backend integration example. The backend uses Express and MongoDB to provide a data endpoint.

Frontend

import useFetcher, { InfiniteScroll } from "endlessflow";
import { Loader2 } from "lucide-react";

const {
  datas: users, // Fetched data
  loading,      // Loading state
  hasMore,      // Indicates if there's more data to fetch
  next,         // Function to fetch the next set of data
} = useFetcher({
  endpoint: "http://localhost:5000/get-data",
});

return (
  <>
    <div>
      {users.map((user) => (
        <div key={user.id}>{user.name}</div>
      ))}
    </div>

    <InfiniteScroll
      hasMore={hasMore}
      isLoading={loading}
      next={next}
      threshold={1}
    >
      {hasMore && (
        <div className="flex font-bold text-xl justify-center items-center my-12">
          <Loader2 className="h-12 w-12 animate-spin text-black" />
          loading....
        </div>
      )}
    </InfiniteScroll>
  </>
);

Backend


const express = require('express')
const mongoose = require('mongoose');
const Item = require('./models/itemSchema');
const app = express()

// Route to fetch data
app.get('/get-data', async function (req, res) {
  try {
    let { limit, skip } = req.query;
  
    // Fetch items from the database with sorting
    const items = await Item.find()
      .skip(skip)
      .limit(limit)
      .exec();

    // Return the items
    res.json(items);
  } catch (err) {
    console.error('Error fetching data:', err);
    res.status(500).json({ error: 'Internal Server Error' });
  }
});