Time-based data
Show data that changes when time passes, such as expired invitations or upcoming events.
Result
A list of upcoming events drops each event within a minute after it starts, without a page reload.
Why the query does not update by itself
Convex runs a query again when the data it read changes. It does not run it again when time passes. Inside a query, Date.now() returns the time when that run started, so a query that compares with Date.now() keeps its old answer until some document changes.
Pass the time as an argument instead. The query then runs again when the argument changes.
Backend
import { v } from 'convex/values'
import { query } from './_generated/server'
export const upcoming = query({
args: { now: v.number() },
handler: async (ctx, { now }) => {
return await ctx.db
.query('events')
.withIndex('by_start', (q) => q.gt('startsAt', now))
.order('asc')
.take(20)
},
})The schema has an index on the start time:
import { defineSchema, defineTable } from 'convex/server'
import { v } from 'convex/values'
export default defineSchema({
events: defineTable({ title: v.string(), startsAt: v.number() }).index('by_start', ['startsAt']),
})Page
Round the time, so that all components in the same minute send the same argument and share one subscription:
<script setup lang="ts">
import { api } from '#convex/api'
const minute = 60_000
const now = ref(Math.floor(Date.now() / minute) * minute)
let timer: ReturnType<typeof setInterval> | undefined
onMounted(() => {
timer = setInterval(() => {
now.value = Math.floor(Date.now() / minute) * minute
}, 10_000)
})
onBeforeUnmount(() => clearInterval(timer))
const events = useConvexQuery(api.events.upcoming, { now }, { keepPreviousData: true })
</script>
<template>
<ul>
<li v-for="event in events.data.value ?? []" :key="event._id">{{ event.title }}</li>
</ul>
</template>keepPreviousData keeps the old list on screen while the next minute's list loads.
Choose the granularity
- A coarser step (a minute, an hour) means fewer new subscriptions. Every new value of
nowis a new query. - When the change must happen at an exact moment, for example when an offer ends, schedule a mutation for that moment with
ctx.scheduler.runAtand store the state in a document. Every open page then updates through the normal subscription.