如何在graphql中使用redux

问题描述

我喜欢graphql。因为它只有一个端点,我只能拉出我需要的数据。

所以我使用 apollo-server 作为服务器,使用 apollo-client 作为客户端。

从 apollo-client 3.0 开始,支持状态管理。

apollo-client的reactive variable函数很方便,不过我更喜欢redux

Redux 工具包还缩短了需要编写的代码长度。

问题是这样的。

  1. 我不能同时使用 apollo-client 3.0 和 redux 吗?

  2. 我不能在 redux 上使用没有 apollo-client 的 graphql 吗?那怎么办?

请检查!

解决方法

了解 GraphQL is just a protocol for describing requests and responses 很重要。但是,是的,“我正在使用 GraphQL”通常也意味着使用智能客户端库,如 Apollo 或 Urql。

当然可以在同一个应用程序中使用 Apollo 和 Redux,但问题变成了您将它们用于。我已在我的帖子 When (and when not) to Reach for ReduxRedux - Not Dead Yet! 中介绍了这一点。总结:

  • 您可以将 Redux 用于任何事情,包括服务器状态缓存和客户端状态
  • Apollo 专为使用 GraphQL 请求缓存服务器状态而构建
  • 如果您唯一使用 Redux 是缓存服务器状态,并且您选择使用 Apollo 来完成该任务,那么您真的不再需要 Redux
  • 但是,如果您真的愿意,您可以使用 GraphQL 处理请求并将该数据放入 Redux 中

值得注意的是,我们有 an upcoming "RTK Query" API for Redux Toolkit that provides a complete data fetching abstractionwe even have a demo of using RTK Query to request and cache data with GraphQL。您可能想尝试一下。