【问题标题】:Apollo Client State - object written to cache with writeData is missingApollo 客户端状态 - 使用 writeData 写入缓存的对象丢失
【发布时间】:2019-07-12 18:36:25
【问题描述】:

我的 React 应用程序中的 Apollo 客户端状态存在问题。我正在通过以下方式创建我的客户端状态链接:

const stateLink = withClientState({
  cache,
  defaults: {
    simulation: {
      __typename: 'Simulation',
      configurationName: null,
      job: null,
      status: null,
      uuid: null,
    },
    pageTitle: null,
  },
  resolvers: {},
});

有时我必须清除应用程序中的缓存(注销后),这也会清除我的客户端状态。我是这样清缓存的:

client.resetStore()

使用withApollo HOC 获取客户端。之后,我尝试通过以下调用重新创建我的本地状态:

client.writeData({
  data: {
    pageTitle: 'test',
  },
});

client.writeData({
  data: {
    simulation: {
      __typename: 'Simulation',
      configurationName: null,
      job: null,
      status: null,
      uuid: null,
    },
  },
});

但它不起作用 - 只有 pageTitle 存储在缓存中,这会导致所有与客户端状态模拟相关的查询失败。

清除前缓存:

{
  "data": {
    "$ROOT_QUERY.simulation": {
      "__typename": "Simulation",
      "configurationName": null,
      "job": null,
      "status": null,
      "uuid": null
    },
    "ROOT_QUERY": {
      "simulation": {
        "type": "id",
        "generated": true,
        "id": "$ROOT_QUERY.simulation",
        "typename": "Simulation"
      },
      "pageTitle": null
    }
  }
}

清除并恢复本地状态后的缓存:

{
  "data": {
    "ROOT_QUERY": {
      "pageTitle": null
    }
  }
}

我也尝试过编写查询,而不是第二个 writeData:

const SIMULATION_LOCAL_DATA_QUERY = gql`
  {
    simulation @client {
      configurationName
      job
      status
      uuid
    }
  }
`;

client.writeQuery({
  query: SIMULATION_LOCAL_DATA_QUERY,
  data: {
    simulation: {
      __typename: 'Simulation',
      configurationName: null,
      job: null,
      status: null,
      uuid: null,
    },
  },
});

但它也没有工作。有人可以告诉我我做错了什么吗?谢谢!

【问题讨论】:

    标签: reactjs apollo react-apollo apollo-link-state


    【解决方案1】:

    查看文档,建议在客户端注销后重置存储的方法是使用 writeDefaults 方法,您可以将其作为回调注入 onRestStore 方法:

    const cache = new InMemoryCache();
    const stateLink = withClientState({ cache, resolvers, defaults });
    
    const client = new ApolloClient({
      cache,
      link: stateLink,
    });
    
    const unsubscribe = client.onResetStore(stateLink.writeDefaults);
    

    这直接来自:https://www.apollographql.com/docs/link/links/state.html

    希望对您有所帮助。

    【讨论】:

    • 谢谢!它有效,但我认为我提出的使用 writeData 的手动方法也应该有效,不幸的是我没有时间研究它。
    猜你喜欢
    • 2019-07-29
    • 2018-07-08
    • 2019-02-15
    • 2017-03-18
    • 2020-03-09
    • 1970-01-01
    • 2021-02-01
    • 2020-08-07
    • 2021-05-25
    相关资源
    最近更新 更多