Trying to get data from merge helper function with Apollo Client InMemoryCache Object, but receive only ref property

584 Views Asked by At

I'm trying get a new set data from a paginated-like API I created but I only receive the object with the ref property from the cache, but the data from the api. How can I return a array of the existing and incoming data?

InMemoryCache Object

const client = new ApolloClient({
  ssrMode: typeof window === undefined,
  link: httpLink,
  cache: new InMemoryCache({
    typePolicies: {
      Query: {
        fields: {
          todos: {
            merge(existing, incoming) {
              console.log(incoming) // I want the data, not the ref object
              return [ ...existing, ...incoming ]
            }
          }
        }
      }
    }
  })
});

photos of the result in console log Result of the Merge Helper Function

useQuery Hook calling the pagination api

if needed I left my repo below

todo client git repo with merge helper function issue

1

There are 1 best solutions below

0
On

You have access to the cache in the third argument to merge, and you can use that to convert the references to data objects.

// assuming these are all the fields on your 
// Todo item's schema
const todoFragment = gql`
fragment todo on Todo {
  id
  name
  completed
}
`;

function merge(existing, incoming, { isReference, cache, variables }) {
  return [
    ...existing ?? [],
    ...incoming.map(x => {
      if (!isReference(x))
        return x; // it's already a data object
      else {
        // convert the Reference to a data object
        return cache.readFragment({
          fragment: todoFragment, // use a fragment with all properties on todo
          id: options.cache.identify(x),
          // only relevant if the objects' fields use variables
          variables,
        });
      }
    }),
  ];
}