簡體   English   中英

我正在從 apollo-link-state 遷移到 @apollo/client,如何在不使用 cache.writeData 的情況下將默認數據寫入 @apollo/client 的 InMemoryCache?

[英]I am migrating from apollo-link-state to @apollo/client, how do I write default data to InMemoryCache of @apollo/client without using cache.writeData?

我使用 react 16.13,目前正在從apollo-client 2.x 遷移到@apollo/client 3.1.1。 我從我的packages.json中刪除了很多依賴庫,因為它們中的大多數現在可以直接從@apollo/client導入。 一切都很順利,直到我從apollo-link-state遷移時扔了一塊名為“刪除默認值”的大石頭。

使用@apollo/client 3.x,我們直接從@apollo/client導入InMemoryCache ,這很好。 但是withClientState鏈接不再存在,並且ApolloClient不支持本地緩存的默認值。 我找不到任何涵蓋此問題的指南。 Angular 有一個指南,但建議使用cache.writeData來構造緩存。 唯一的問題是,在 v3.x 的@apollo/client中, InMemoryCache不再有writeData方法。 有一種modify方法,但它也不是很容易使用,至少我無法讓它為此目的工作。

我有一個很大的“默認值”object:

export default {
  authentication: {
    __typename: 'authentication',
    auth: ''
  },
  UserInfo: {
    __typename: 'UserInfo',
    employee: {
      __typename: 'UserInfoEmployee',
      defaultShopId: '',
      id: '',
      email: '',
      image: {
      __typename: 'image',
      id: '',
      url: ''
    },
    firstName: '',
    lastName: '',
    manager: '',
    boss: ''
    },
    countryCode: '',
    chainId: ''
  },
  defaultShop: {
    __typename: 'defaultShop',
    id: '',
    name: '',
    timeZone: null
  },
  locale: {
    __typename: 'locale',
    locale: getBrowserLocale()
  },
  countries: {
    __typename: 'countries',
    data: []
  },
  Products: {
    __typename: 'Products',
    guid: 0,
    ProductTypes: {
      __typename: 'ProductTypes',
      TypeNumber: 0,
      type: ''
    },
    legacyConfiguration: false,
    version: '1.0.0'
  },
  location: {
    __typename: 'location',
    pathname: '',
    search: '',
    hash: null,
    action: '',
    key: null,
    isQueryActive: false,
    query: null
  }
}

我應該如何在不使用cache.writeData情況下將這些默認數據寫入InMemoryCache

它需要使用策略編寫,cache.writeQuery 在初始化時對我不起作用,

 cache.policies.addTypePolicies({
    Query: {
      fields: {
        selectedCurrency: {
          read() {
            return "USD";
          },
        },
        selectedIndex: {
          read() {
            return 0;
          },
        },
        bookingFlowStep: {
          read() {
            return '';
          },
        },
        
      },
    },
  });

請改用writeQuery 我相信在 v3 中,他們轉向使用一種通用方式來設置默認 state。

官方文檔

    const query = gql`
        query {
            authentication @client {
                id
                __typename
            }
            ...
        }`
    cache.writeQuery({
        query,
        data: {
            authentication: {
                __typename: 'authentication'
               ...
        }
    })

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM