Ad

React Apollo Client - Modify Query Data Before It Goes To Cache

Is there a way to modify query response data before it is saved in the internal cache? I'm using apollo hooks, but this question is relevant to any of front-end approaches using apollo client (HOC & Components as well).

const { data, updateQuery } = useQuery(QUERY, {
  onBeforeDataGoesToCache: originalResponseData => {
    // modify data before it is cached? Can I have something like this? 
    return modifiedData;
  }
});

Obviously onBeforeDataGoesToCache does not exist, but that's exactly the behavior I'm looking for. There's an updateQuery function in the result, which basically does what is needed, but in the wrong time. I'm looking for something to work as a hook or a middleware inside the query mutation.

Ad

Answer

It sounds like you want Afterware which, much like Middleware that allows operations before the request is made, allows you to manipulate data in the response e.g.

const modifyDataLink = new ApolloLink((operation, forward) => {
  return forward(operation).map(response => {
    // Modify response.data...

    return response;
  });
});

// use with apollo-client
const link = modifyDataLink.concat(httpLink);
Ad
source: stackoverflow.com
Ad