Medium
Pagination Merge
The social feed below implements infinite scroll pagination using fetchMore. When the user clicks "Load More", the query runs with a new offset, but the existing posts disappear and only the new batch is shown. Your task: 1. Configure a type policy with a merge function for the "posts" field so Apollo merges old and new results. 2. Keep the fetchMore call and update the offset variable. 3. Provide keyArgs so Apollo knows how to cache different filter combinations. The query signature: query GetPosts($offset: Int!, $limit: Int!) { posts(offset: $offset, limit: $limit) { id content author createdAt } }
Problem Code
import React, { useState } from 'react';import { useQuery, gql } from '@apollo/client';const GET_POSTS = gql`query GetPosts($offset: Int!, $limit: Int!) {posts(offset: $offset, limit: $limit) {idcontentauthorcreatedAt}}`;const LIMIT = 10;const SocialFeed = () => {const [offset, setOffset] = useState(0);// Bug: fetchMore replaces results instead of appendingconst { data, loading, fetchMore } = useQuery(GET_POSTS, {variables: { offset: 0, limit: LIMIT },});const handleLoadMore = () => {const nextOffset = offset + LIMIT;setOffset(nextOffset);fetchMore({variables: { offset: nextOffset, limit: LIMIT },});};if (loading && !data) return <p>Loading feed...</p>;return (<div><h1>Social Feed</h1><ul>{data?.posts.map((post: { id: string; content: string; author: string; createdAt: string }) => (<li key={post.id}><p>{post.content}</p><small>{post.author} — {post.createdAt}</small></li>))}</ul><button onClick={handleLoadMore} disabled={loading}>Load More</button></div>);};// Bug: no cache configuration — needs InMemoryCache with typePolicies// const client = new ApolloClient({// uri: '/graphql',// cache: new InMemoryCache(),// });export default SocialFeed;
App.tsx