Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
298 views
in Technique[技术] by (71.8m points)

reactjs - Update the apollo cache without calling the graphql server (apollo v3.3)

I'm building a react app, I have a datasheet and update directly on the data stream I want when I send data to graphql server for update and get true result then I will update apollo cache with cache.writeQuery

  • The problem is that when the following code is executed, there is also a request to the graphql server to get the data from the whole table and update the cache, I don't want to request to the graphql server to work. There, I want to update from the browser. So where did I go wrong?

here is my code

updateInventoryCache: async (_, { inventory, productId, variables }, { cache }) => {
      let variablesData;
      if (variables) {
        variablesData = JSON.parse(variables);
      }
      const { getListProduct } = cache.readQuery({
        query: GET_PAGING_PRODUCT,
        variables: variablesData.variables
      });
      cache.writeQuery({
        query: GET_PAGING_PRODUCT,
        variables: variablesData.variables,
        data: {
          getListProduct: {
            ...getListProduct,
            products: getListProduct.products.map((product) => {
              if (product.id === productId) {
                return {
                  ...product,
                  inventory
                };
              }
              return product;
            })
          }
        }
      });
      return true;
    }

"@apollo/client": "^3.3.7"

update 1:

I will initially call the graphql server to get the data and store it in apollo's (cache-and-network) cache. Then I want to update that data in the cache without having to call the apollo server to refetchQueries As in the post, I used the client.writeQuery function to update the cache but instead of updating at the client, apollo called the graphql server to get new data and update the cache while I was not using refetchQueries.

update 2: I checked, my cache has been updated but my UI doesn't re-render

question from:https://stackoverflow.com/questions/66050258/update-the-apollo-cache-without-calling-the-graphql-server-apollo-v3-3

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use fetchPolice="cache-only" to use only the cache https://www.apollographql.com/docs/react/data/queries/#setting-a-fetch-policy


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...