amitlzkpa
amitlzkpa3mo ago

I am working on a project where I am

I am working on a project where I am using the useQuery hook to connect data with my React application. It's a simple query which fetches a document based on the id. However I don't have the id at hand on initialization. I maintain a state variable to keep track of the currently loaded document id which can be dynamically loaded or empty. What would be a good pattern to link this state variable with the useQuery hook? React
const [currDocId, setCurrDocId] = useState("");
const docData = useQuery(api.documents.getDocumentById, { docId: currDocId });
const [currDocId, setCurrDocId] = useState("");
const docData = useQuery(api.documents.getDocumentById, { docId: currDocId });
Convex Query
export const getDocumentById = query({
args: {
docId: v.optional(v.id("documents")),
},
handler: async (ctx, args) => {
if (!args?.docId) return null;
const dbId = args.docId;
const document = await ctx.db.get(dbId);
return document;
},
});
export const getDocumentById = query({
args: {
docId: v.optional(v.id("documents")),
},
handler: async (ctx, args) => {
if (!args?.docId) return null;
const dbId = args.docId;
const document = await ctx.db.get(dbId);
return document;
},
});
2 Replies
Hmza
Hmza3mo ago
You can use "skip" argument useQuery(api.documents.getDocumentById, currDocId ? { docId: currDocId } : "skip");
amitlzkpa
amitlzkpaOP3mo ago
Thanks! I'll give that a try.

Did you find this page helpful?