Nizar Zizoune
Nizar Zizoune

Reputation: 514

Apollo Graphql fetchMore, updateQuery does not update state

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.

Upvotes: 8

Views: 6059

Answers (1)

Nizar Zizoune
Nizar Zizoune

Reputation: 514

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,
})

Upvotes: 5

Related Questions