DaReal
DaReal8mo ago

Errors Using Queries in Client

Hello Support, I am using the current query which fetches info about the currently logged user from the code snippet: https://docs.convex.dev/auth/database-auth#mutations-for-upserting-and-deleting-users However, because the useQuery is a hook, i am using the "use client" at the top of the file and i am getting an async error just like in the picture attached. If i extract the query to its own component, i still get an error. How can i fix this please? Thanks in advance.
Storing Users in the Convex Database | Convex Developer Hub
You might want to store user information directly in your Convex database, for
No description
9 Replies
DaReal
DaRealOP8mo ago
@Michal Srb @erquhart
erquhart
erquhart8mo ago
Sharing the code that's causing the error would help. query is backend, useQuery is frontend. You can only use query() in your convex directory, sounds like you're using it in a component.
DaReal
DaRealOP8mo ago
I am using useQuery actually. Below is the code in the user.ts file in my convex directory: export const current = query({ args: {}, handler: async (ctx) => { return await getCurrentUser(ctx); }, }); export async function getCurrentUser(ctx: QueryCtx) { const identity = await ctx.auth.getUserIdentity(); if (identity === null) { return null; } return await userByClerkId(ctx, identity.subject); } And i call it like so on the frontend: const user = useQuery(api.users.current);
entropy
entropy8mo ago
It might be something else in your client component/page.
DaReal
DaRealOP8mo ago
The page renders fine without using the useQuery hook
entropy
entropy8mo ago
hmm my only other guess would be to double check you are importing from convex/react. import { useQuery } from 'convex/react'
DaReal
DaRealOP8mo ago
I figured it out, thanks. I simply had to check if the query wasn't undefined or null: const userInvestment = useQuery(api.investments.getUserInvestment); // Handle loading state by checking if userInvestment is undefined if (userInvestment === undefined) { return <div>Loading...</div>; } // Handle error state if necessary (assuming your function may throw an error) if (userInvestment === null) { return <div>Error: Unable to fetch investment details.</div>; } But i actually handled the error in the query function. I do not know why i have to handle the error again on the front end. (I am not a pro developer, incase i sound stupid lol) The convex query with error handling: const userInvestment = await ctx.db .query("investments") .withIndex("by_user", (q) => q.eq("user", userID._id)) .unique(); if (!userInvestment) { throw new ConvexError("Investment cannot be found for user!"); } else { } return userInvestment;
erquhart
erquhart8mo ago
undefined/null values wouldn't cause that error, though. But glad you got it figured 👍
DaReal
DaRealOP8mo ago
same thing i was wondering

Did you find this page helpful?