首页 > 解决方案 > 从 ApolloClient 的请求中获取 clientState 数据以用于 operation.setContext 反应 apollo graphql

问题描述

React - Apollo - GraphQl 大家好,代码是:

const client = new ApolloClient({
  uri: "http://someurl.com/graphqlserverendpoint/",
  fetchOptions:{
    credentials : "include" 
  },
  request : operation => { 
    // i want to access needed data from here
  const neededDataFromClientState = "QueryDataFromHere!!!"
  const token = localStorage.getItem('authToken') || "" ; 
    operation.setContext({
      headers: {
        Authorization : `JWT ${token}` 
      }
    })

  },
  clientState : {  
    defaults : { 
      isLoggedIn : !!localStorage.getItem('authToken') ,  
      neededData : "the data I want get"

    }
  }
});

我想从请求操作中访问名为 requiredData 的数据

有没有人想帮助我?谢谢..

标签: reactjsgraphqlapollo-client

解决方案


您没有提供导入 - 您ApolloClient来自apollo-boost项目,这就是为什么它的配置选项不同于从apollo-client.

过时的

Apollo Boost 项目现已退役,因为 Apollo Client 3.0 提供了类似的简单设置。我们建议删除所有apollo-boost依赖项并ApolloClient根据需要修改您的构造函数。

Apollo boost一个“简单的入门”项目,旨在隐藏一些配置复杂性([几行更多]缓存和链接配置)。

解决方案

使用文档中描述的普通、广为人知的身份验证方法和许多类似教程

localStorage用于保持用户登录页面/浏览器刷新。

其他数据可以通过上下文在链接之间传递——数据可以完全存储在外部,如token例所示。其他(在链之后,顺序很重要)链接[-s] 可以使用operation.getContext().tokenlocalStorage 从上下文中读取数据。


推荐阅读