React Apollo Client - modify query data before it goes to cache

白昼怎懂夜的黑 提交于 2020-01-14 05:08:06

问题


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.


回答1:


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);


来源:https://stackoverflow.com/questions/58391617/react-apollo-client-modify-query-data-before-it-goes-to-cache

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!