0

I have created an infinite scrolling using react-virtouso. and it is working proper too. in the given example it fetch data when we scroll-down and when we reach on the end, and it append to existing data.

when we scroll-up it show the already fetch data.

I need to find a way to fetch new data, when we scroll-up instead of showing already fetch data.


const app = () => {
  const [currentPage, setCurrentPage] = useState(1);
  const [data, setData] = useState([]);

  const fetchData = async () => {
    fetch(`https://dummyapi.io/data/v1/user?limit=10&page=${currentPage}`)
      .then(response => response.json())
      .then(result => {
        setData(data => [...data, ...result.data]);
        setCurrentPage(page => page + 1);
      })
      .catch(error => console.log("error", error));
  };

  return( 
     <Virtuoso
        style={{ height: 1000 }}
        data={data}
        endReached={fetchData}
        itemContent={(index, data) => {
          let bgColor = "";
          if (index % 2 === 0) {
            bgColor = "yellow";
          } else {
            bgColor = "blue";
          }

          return (
            <div style={{ background: bgColor }}>
              <div>{data.name}</div>
            </div>
          )}
        }
     />
   )}



shafa vp
  • 89
  • 7

1 Answers1

0

If you want to achieve infinite scrolling when you scroll up then you can modify the behavior like this.

  1. Create a fetchNewData function that can handle fetching new data.
  2. Use the startReached prop for Virtuosa and find if the user reached the top.
  3. Call the function and prepend the response data to your existing data.

Here is a revised code for your use case:

  const fetchData = async (page) => {
    try {
      const response = await fetch(`https://dummyapi.io/data/v1/user?limit=10&page=${page}`);
      const result = await response.json();
      return result.data;
    } catch (error) {
      console.log("error", error);
      return [];
    }
  };

  // Function to fetch new data when scrolling up
  const fetchNewData = async () => {
    const newData = await fetchData(currentPage);
    if (newData.length > 0) {
      setData((prevData) => [...newData, ...prevData]);
      setCurrentPage((prevPage) => prevPage + 1);
    }
  };

  useEffect(() => {
    // Fetch initial data on component mount
    fetchData(currentPage).then((initialData) => setData(initialData));
  }, []);

  return (
    <Virtuoso
      style={{ height: 1000 }}
      data={data}
      endReached={fetchData.bind(null, currentPage + 1)} // Fetch data when scrolling down
      startReached={fetchNewData} // Fetch data when scrolling up to the top
      itemContent={(index, data) => {
        let bgColor = index % 2 === 0 ? "yellow" : "blue";
        return (
          <div style={{ background: bgColor }}>
            <div>{data.name}</div>
          </div>
        );
      }}
    />
  );
  • really thank you for your solution, and I have small doubt, when we fetch data in up direction, how the pagination is handled, it should be minuses right ? and how the pagination handle is in end reach also ? and what the bind is doing ? – shafa vp Jul 26 '23 at 11:34