reactjs - 从 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 的数据
有没有人想帮助我?谢谢..
解决方案
您没有提供导入 - 您ApolloClient
来自apollo-boost
项目,这就是为什么它的配置选项不同于从apollo-client
.
过时的
Apollo Boost 项目现已退役,因为 Apollo Client 3.0 提供了类似的简单设置。我们建议删除所有
apollo-boost
依赖项并ApolloClient
根据需要修改您的构造函数。
Apollo boost是一个“简单的入门”项目,旨在隐藏一些配置复杂性([几行更多]缓存和链接配置)。
解决方案
使用文档中描述的普通、广为人知的身份验证方法和许多类似的教程
localStorage
用于保持用户登录页面/浏览器刷新。
其他数据可以通过上下文在链接之间传递——数据可以完全存储在外部,如token
本例所示。其他(在链之后,顺序很重要)链接[-s] 可以使用operation.getContext().token
localStorage 从上下文中读取数据。
推荐阅读
- vue.js - 如何从组件(b-card)传递选定的选项并将其传递给vue中的多选组件
- clickhouse - clickhouse-client 收到错误“从套接字读取时超时”
- mongodb - 如何使用聚合从 mongoDB 中对象的嵌套数组中提取信息
- c++ - C++:在一个类中实现一个接口或一个可选接口的多个实例
- node.js - 如何解决无法读取未定义的属性“原型”
- c# - Task.CompletedTask 的 ValueTask 等价物是什么?
- javascript - 处理邮递员快递发回的错误
- react-native - 反应导航中未定义参数
- python - Python:如何获取函数中条目的值
- javascript - 未捕获的语法错误:意外的标记“<”