Apollo client 緩存問題


  • administrators

    Apollo client 聲稱他們把緩存玩的很好,用過以後才知道其實不然。
    更新緩存,還是很手動的活。比如:

     <Mutation
              mutation={DELETE_CUSTOMPAGE}
              key={item.draftid}
              update={cache => {
                const { customPages } = cache.readQuery({ query: GET_CustomPages });
                const newCustomPages = [...customPages];
                const idx = _.findIndex(newCustomPages, {
                  id: item.id
                });
    
                if (idx > -1) {
                  newCustomPages.splice(idx, 1);
                }
    
                cache.writeQuery({
                  query: GET_CustomPages,
                  data: { customPages: newCustomPages }
                });
              }}
            >
    

    在同一個模塊,加這些cache處理還不算太麻煩,問題是另一個模塊要用到其他模塊,要保證其他模塊修改後,通知所有相關模塊也更新對於的QUERY是極其麻煩的。

    因此,有人問題這個問題 - 如何把緩存關閉:
    https://stackoverflow.com/questions/47879016/how-to-disable-cache-in-apollo-link-or-apollo-client

    其中一位大哥的答案(非選中的)解決了我的問題:

    I would always suggest not to disable inbuild caching feature from apollo client. Instead you can always set fetchPolicy: 'network-only' for an individual queries. Something like this

    <Query
        query={GET_DOG_PHOTO}
        variables={{ breed }}
        fetchPolicy='network-only'
    >
     {({ loading, error, data, refetch, networkStatus }) => {
       ...
     }}
    </Query>
    

    While fetching data with this Query, it would always do a network request instead of reading from cache first.