Apollo客户端状态-缺少使用writeData写入缓存的对象

时间:2019-02-19 09:46:35

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

我的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,
    },
  },
});

但是它也不起作用。有人可以告诉我我在做什么错吗?谢谢!

1 个答案:

答案 0 :(得分:0)

仔细阅读文档,建议在客户端注销后重置商店的方法是使用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

希望有帮助。

相关问题