#useQuery but only after logged in
4 messages · Page 1 of 1 (latest)
Hi @teal patrol. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:
To ensure that a Convex useQuery only runs after the user is logged in, you should check the authentication state before executing the query. The recommended approach is to use the useConvexAuth() hook to determine if the user is authenticated, and then pass "skip" to useQuery if not. This prevents the query from running until authentication is confirmed.
Here’s a common pattern:
import { useConvexAuth, useQuery } from "convex/react";
import { api } from "../convex/_generated/api";
export default function MyComponent() {
const { isLoading, isAuthenticated } = useConvexAuth();
// Only run the query if authenticated, otherwise skip
const data = useQuery(
api.users.getCurrentUser,
isAuthenticated ? {} : "skip"
);
if (isLoading) return <div>Loading...</div>;
if (!isAuthenticated) return <div>Please log in</div>;
return <div>Welcome, {data?.name}</div>;
}
This pattern is officially recommended in the Convex documentation and community support channels. You can also create custom hooks to encapsulate this logic for reuse across your app. The key is to always use "skip" as the query argument when the user is not authenticated, which prevents errors and unnecessary backend calls [Convex & Clerk: React](https://docs.convex.dev/auth/clerk#react) [Authentication Best Practices: Convex, Clerk and NextJs](https://stack.convex.dev/authentication-best-practices-convex-clerk-and-nextjs#ensuring-authentication-in-client-components) [Discord: Invalid hook call](https://discord.com/channels/1019350475847499849/1380513714767138917).
Summary:
- Use useConvexAuth() to check authentication.
- Pass "skip" to useQuery if not authenticated.
- Optionally, wrap your query-calling components in <Authenticated> from convex/react for additional safety.