I'm using SWR to fetch data as stated in the docs:
function App () {
const [pageIndex, setPageIndex] = useState(0);
// The API URL includes the page index, which is a React state.
const { data } = useSWR(`/api/data?page=${pageIndex}`, fetcher);
// ... handle loading and error states
return <div>
{data.map(item => <div key={item.id}>{item.name}</div>)}
<button onClick={() => setPageIndex(pageIndex - 1)}>Previous</button>
<button onClick={() => setPageIndex(pageIndex + 1)}>Next</button>
</div>
}
The only difference in my case is I'm loading more items on the same page (so more like infinite scroll not pagination), but here's the trouble:
const { data } = useSWR(`/api/data?page=${pageIndex}`, fetcher);
Notice how data is fetched based on pageIndex
variable, that comes from the state. Once it changes everything rerenders, so instead of getting more items every time user clicks on a button I'm always getting a refresh, then user sees initial render, then new items. So in short I want to load more items at the bottom of the page, not refresh everything and then add the items... What am I missing? There's useSWRInfinite, but it's the same story, it gets url data from the state...
Comments
Post a Comment