Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 793
Mihail Avatar asked Oct 29 '25 15:10

Mihail


1 Answers

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);
like image 175
Tom Avatar answered Oct 31 '25 08:10

Tom



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!