Updating fetchMore data in cache does not trigger useEffect

I have a poorly designed architecture we are currently hitting a limit with. Without going into unecessary detail, we are having to use fetchMore to get some additional data. My understanding is that the following:

  const { data: commentsData, fetchMore: fetchMoreComments } = useQuery(SEARCH_COMMENTS, {
    variables: {
      filter: {
        bugID: { eq: id }
      },
      limit: 50
    },    
    onCompleted: (data) => {      
      if(data.searchComments?.nextToken){
        setCommentsToken(data.searchComments?.nextToken); // amplify pagination 
      }
    }
  });

This works and grabs the data, whenever the server responds with a nextToken React knows to call the fetchMore again.

useEffect(async () => {
    if(commentsToken){
      const moreComments = await fetchMoreComments(
        {
          variables: {
            nextToken: commentsToken 
          }
      })  
     ....code to manually concatenate results

I’ve also written a merge function

const cache = new InMemoryCache({
  typePolicies: {
    Query: {
      fields: {
        searchComments: {
          // Don't cache separate results based on
          // any of this field's arguments.
          keyArgs: ["id"],

          // Concatenate the incoming list items with
          // the existing list items.
          merge(existing = [], incoming = []) {
            return [...existing, ...incoming.items];
          },
        },.....

And am seeind the full results in the Cache via the Apollo inspector:

I would assume this would cause a change in the commentsData tuple but no change is detected. Is the intended flow to manually concatenate the results based on some implementation specific change? (in this case nextToken is watched). My assumption was that because the cache was updated it would update the data on its own, thinking infinite scroll.

whenever the server responds with a nextToken React knows to call the fetchMore again.

You did not include any code for this part (calling fetchMore), could you please add that as well?


Thanks @lenz my train of thought rolled right on by this most important aspect.

1 Like

Hi there, I’m sorry for the late reply. For me, your merge function looks suspicious - it seems to change the shape of the query somehow, so it should probably either be return [...existing, ...incoming], or { ...existing, ...incoming, items: [...existing.items, ...incoming.items] }.

Generally, it is very hard to give feedback in these cases, since there are just so many things going on. Could you maybe create a small reproduction of this?