Patolord
Patolord6mo ago

How do I count items on a table?

I want to do the equivalent of this: SELECT COUNT(*) FROM table_name; In Convex i tried this but it seems not performant: export const countMaterialsTable = query({ handler: async (ctx) => { const materials = await ctx.db.query("materials").collect(); return materials.length; }, I Installed convex cache helper thinking it may help since i dont need the counter to be that reactive. - ConvexQueryCacheProvider (provider.tsx) - UseQuery (hooks.ts) import { useQuery } from "convex-helpers/react/cache/hooks"; // ... const materials = useQuery(api.materials.countMaterialsTable); It worked fine on the development server, but when i deployed to vercel my cache was not working ( i attached the console.log on debug mode, it loops every 5 seconds or so), between the actual value "185" and undefined.
No description
3 Replies
erquhart
erquhart6mo ago
I'd recommend keeping a computed field on your table that stores the count. Increment on insert, decrement on delete. Everything is transactional so it just works. Or, rather, not on that same table, but a separate table.
mango/elee
mango/elee6mo ago
also a potential feature request for the table to be able to have associated metadata
Patolord
PatolordOP6mo ago
so i should just make a metadata table? seems ok