8

I'm currently trying to implement pagination on my posts. Using Apollo graphql here is my useQuery

const { data: postsData, fetchMore } = useQuery(POSTS_BY_USER_DRAFT, {
fetchPolicy: 'network-only',
variables: {
  user: user.id,
  start: 0,
  limit: limit
},
onCompleted: () => {
  setTotal(postsData[model].meta.pagination.total)
}})

and here is my onClick handler for fetching more posts

const loadMorePosts = async () => {
const nextStart = start + limit
setStart(nextStart);
await fetchMore({
  variables: {
    user: user.id,
    offset: nextStart,
    limit: limit,
  },
  updateQuery: (prevResult, { fetchMoreResult }) => {
    if (!fetchMoreResult) {
      return prevResult
    }
    const prevData = prevResult[model].data
    const moreData = fetchMoreResult[model].data

    fetchMoreResult[model].data = [...prevData, ...moreData]
    // fetchMoreResult[model].data = [...moreData]
    return fetchMoreResult
  },
})}

My queries are successful as I do get correctly the data, however postsData does not get updated

[NOTICED]: If I switch fetchMoreResult[model].data = [...prevData, ...moreData] for fetchMoreResult[model].data = [...moreData] my postsData does get updated.

I have tried return { ...fetchMoreResult } and multiple ways of returning data fearing an immutability/comparaison issue but it does not seem to do the job.

1 Answer 1

5

I'm not sure why, but setting a fetchPolicy for Apollo will do the job

const client = new ApolloClient({


link: authLink.concat(httpLink),
  cache: new InMemoryCache({
    typePolicies: {
      Publication: {
        merge: true,
      },
      Post: {
        merge: true,
      },
    },
  }),
  defaultOptions: defaultOptions,
})
Sign up to request clarification or add additional context in comments.

2 Comments

I had the same issue using MongoDB Realm and your answer helped me realize that I needed a typePolicy for each custom resolver that made use of fetchMore or refetch.
This is a requirement of Apollo's InMemoryCache: apollographql.com/docs/react/caching/cache-configuration/… Just wanted to share the why :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.