I'm building a messaging app with my team, and one of the things we realised recently is that our API has a hard limit on it. We can't fetch all of a users' message threads in one go due to rate limits, so we have to use the relay style, cursor-based pagination that the API team have introduced.
Implementing this pagination in our application was super easy, largely thanks to two things: (1) this post about pagination with Apollo by Emma on her personal blog and (2) Realising that Apollo have a relay-style pagination helper already which is a doddle to implement.
But when I wanted to test this implementation, there was very little documentation on how to test fetchMore
Here's my implementation:
const {
loading,
error,
data,
fetchMore,
} = useQuery(THREAD_LIST_QUERY, {
variables: {
ThreadsInput: {
limit: 50,
},
},
});
useEffect(() => {
if (data && fetchMore) {
const nextPage = getHasNextPage(data);
const after = getAfter(data);
if (nextPage && after !== null) {
fetchMore({
updateQuery,
variables: {
ThreadsInput: {
limit: 50,
cursor: after,
},
},
});
}
}
}, [data, fetchMore]);
If you're wondering about the contents of the getHasNextPage
and other functions in this snippet, head over to Emma's blog I mentioned at the outset.
In the rest of my test suite, I have my mocks like this:
<MockedProvider
mocks={mocks}
>
<Threads />
</MockedProvider>
What I hadn't noticed before is the significance of why mocks
is an array: it's so you can pass multiple mocks ... sequential ones:
<MockedProvider
mocks={[β¦mocks, fetchMoreMocks]}
addTypename={false}
>
<Threads />
</MockedProvider>
It's as easy as that!
I'm glad we have such a comprehensive suite of tools in Apollo, but they can't cover everything in their documentation, it's already quite comprehensive. Still, this was a delightful discovery I wanted to pass on to you!
Top comments (0)