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?
CodePudding user response:
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 get undefined
.
You can confirm this by logging out the loading
variable - you'll see it's true
- the query is "in flight" and data
will continue to be undefined
until loading
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
:
const { data, loading, error } = useUserQuery();
if (loading) return 'Loading...';
// At this point we either have an error or data; handle it
console.log(`data:${data}`)
console.log(`error:${error}`)
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 a useEffect()
, you can then do something once it has become available:
const { data, error } = useUserQuery();
useEffect(() => {
// Always check for an error first:
if (error) {
console.log(`error:${error}`)
}
if (data) {
// Handle the data
console.log(`data:${data}`)
}
}, [data, error]);
...
// Always return the UI
return (
...
);