Graphql 查询在 graphql 服务器上运行良好,但在客户端上运行不佳
我有一个解析器用于检查用户登录是否
// ______________________________Check if user logged in____________________________________
@Query((_return) => User, { nullable: true })
async user(@Ctx() { req }: Context): Promise<User | null | undefined> {
console.log(req.session.userId)
if (!req.session.userId) return null;
else{
return await User.findOne(req.session.userId)
}
}
在 http://localhost:4000/graphql 上工作,但是当我在客户端(React)上查询时,它返回未定义。
客户端查询代码
const { data, loading, error } = useUserQuery();
console.log(`data:${data}`)
console.log(`error:${error}`)
我使用 codegen 生成 useUserQuery() ,它就像
export function useUserQuery(baseOptions?: Apollo.QueryHookOptions<UserQuery, UserQueryVariables>) {
const options = {...defaultOptions, ...baseOptions}
return Apollo.useQuery<UserQuery, UserQueryVariables>(UserDocument, options);
}
我客户端上的 cookie 仍然存在,但它不起作用,我该如何修复它?
I have a resolver for check user login or not
// ______________________________Check if user logged in____________________________________
@Query((_return) => User, { nullable: true })
async user(@Ctx() { req }: Context): Promise<User | null | undefined> {
console.log(req.session.userId)
if (!req.session.userId) return null;
else{
return await User.findOne(req.session.userId)
}
}
it work on http://localhost:4000/graphql, but when i query on client(React) it return undefined.
code for query at client
const { data, loading, error } = useUserQuery();
console.log(`data:${data}`)
console.log(`error:${error}`)
i use codegen for generate useUserQuery(), it like
export function useUserQuery(baseOptions?: Apollo.QueryHookOptions<UserQuery, UserQueryVariables>) {
const options = {...defaultOptions, ...baseOptions}
return Apollo.useQuery<UserQuery, UserQueryVariables>(UserDocument, options);
}
my cookie on client still existing ,but it just not work, how can i fix it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的 Apollo 查询将需要有限的时间才能返回答案;这就是为什么当您立即记录
${data}
时,您会得到undefined
。您可以通过注销
loading
变量来确认这一点 - 您会看到它是true
- 查询“正在运行”并且data
将继续在loading
变为 false 之前,将处于未定义
状态。因此,处理此问题的一个非常简单的方法可能是 this Apollo 文档示例 - 在我们
加载
时提前返回:如果您有能力在数据到达之前“停止世界”(或至少是 UI),那很好,但是一般来说我喜欢尽可能多地进行渲染,并使用
useEffect()
“监听”data
,一旦它可用,您就可以执行某些操作:Your Apollo query will take a finite amount of time to come back with an answer; that's why when you immediately log
${data}
you getundefined
.You can confirm this by logging out the
loading
variable - you'll see it'strue
- the query is "in flight" anddata
will continue to beundefined
untilloading
goes false.So a very simple way to handle this might be as in this Apollo docs example - just return early while we're
loading
:That's fine if you can afford to "stop the world" (or at least the UI) until the data has arrived, but generally I like to get on with rendering as much as I can and "listen" to the
data
with auseEffect()
, you can then do something once it has become available: