danbovey / react-infinite-scroller

⏬ Infinite scroll component for React in ES6
https://danbovey.uk/react-infinite-scroller/
MIT License
3.3k stars 509 forks source link

react hooks. hasMore does not work well. #273

Open johnvonneumann7 opened 3 years ago

johnvonneumann7 commented 3 years ago

api server: django If res.data.next is null, I want to disable the next reload, but the following code will disable it after one round, and if the page has up to 3, it will get up to 4, and I will get a 404 error.

import React, { useState } from 'react';
import InfiniteScroll from 'react-infinite-scroller';
import axios from 'axios';
import Box from '@material-ui/core/Box';
import Grid from '@material-ui/core/Grid';
import CircularProgress from '@material-ui/core/CircularProgress';
import { Video } from '../components/Types';
import VideoCard from '../components/VideoCard';

type Props = {
  to: string;
  tag?: string;
};

export default function VideoList(props: Props) {
  const [data, setData] = useState<Video[]>([]);
  const [hasMore, setHasMore] = useState(true);

  const loadMore = (page: number) => {
    axios
      .get(`/api/videos/${props.to}`, {
        params: { page: page, tag: props.tag },
      })
      .then((res) => {
        setData([...data, ...res.data.results]);
        if (!res.data.next) setHasMore(false);
      });
  };

  return (
    <InfiniteScroll
      pageStart={0}
      loadMore={loadMore}
      hasMore={hasMore}
      loader={
        <Box key={0} textAlign="center">
          <CircularProgress />
        </Box>
      }
    >
      <Grid container spacing={2}>
        {data.map((video) => (
          <Grid key={video.pk} item xs={12} sm={6} md={4} lg={3} xl={2}>
            <VideoCard video={video} />
          </Grid>
        ))}
      </Grid>
    </InfiniteScroll>
  );
}

image image

What should I do in this case?

apenab commented 3 years ago

I would recommend using react-query with the function Inifinity Query. I use that package with this package and it's work properly.

jack-annexdistribution commented 2 years ago

You may just have to call setHasMore before you call setData