I’ve got a super basic offset pagination setup on a blog website. There’s a homepage component with an entry listing, and a single page component for the post detail. I’m using offsetLimitPagination() to load new entries at the bottom of the list.
Query Cache:
const queryCache = new InMemoryCache({
typePolicies: {
Query: {
fields: {
entries: offsetLimitPagination()
},
},
},
});
Homepage component:
export default function Home() {
const queryOffset = useRef(0);
const queryVariables = {
section: ['blog'],
limit: 4,
offset: queryOffset.current
}
const { error, data, fetchMore } = useQuery(GET_BLOG_ENTRIES, { variables: queryVariables });
const handleLoadMore = () => {
fetchMore({
variables: {
offset: queryOffset.current += queryVariables.limit
}
});
}
return (
<>
<ul>
{ data.entries.map( (entry) => (
<li key={entry.id}>
<a href={entry.uri}>
<h6>{entry.title}</h6>
</a>
</li>
)) }
</ul>
<button onClick={handleLoadMore}>Load More</button>
</>
);
}
Here’s my problem:
- The user clicks “load more” a couple of times, adding entries to the listing cache
- The user clicks on an entry link, navigating away from the homepage component to the post detail component
- The user clicks the back button, Apollo loads all of the entries in the cache, but the
pagerOffsetvariable has been reset to 0 because the component re-mounted - The user clicks “load more” again and gets the first set of entries repeated because the offset is back to 0
What’s the recommended way of handling this? Should I figure out how to make the offset value persist between components? Or should I modify Apollo’s read() function somehow?