oscklmO
Convex Community3y ago
11 replies
oscklm

Confused with passing additional arguments to paginated query

Hello,

So i'm trying to play around with passing paginated messages, and when i pass additional arguments to the query, it breaks something.

// convex/messages.ts
export const all = query({
  args: { paginationOpts: paginationOptsValidator, channelId: v.string() },
  handler: async (ctx, args) => {
    const channelId = ctx.db.normalizeId('channels', args.channelId)

    if (!channelId) return
    // Grab the most recent messages.
    const result = await ctx.db
      .query('messages')
      .withIndex('by_channel', (q) => q.eq('channelId', channelId))
      .order('desc')
      .paginate(args.paginationOpts)

    return {
      ...result,
      page: (await enrichMessages(ctx, result.page)).reverse(),
    }
  },
})

async function enrichMessages(ctx: QueryCtx, messages: Doc<'messages'>[]) {
  return await async.map(messages, (message) => enrichMessage(ctx, message))
}

async function enrichMessage(ctx: QueryCtx, message: Doc<'messages'>) {
  const author = await ctx.db.get(message.authorId)
  if (author === null) {
    return null
  }
  return { ...message, author }
}



// message-list.tsx
const MessageList: FC<MessageListProps> = ({ channelId }) => {
  const {
    results: messages,
  } = usePaginatedQuery(
    api.messages.all,
    { channelId },
    { initialNumItems: 25 }
  )
  if (!messages) return <div>Loading...</div>

  return (
    <div className="space-y-2">
      {messages.map((message) => {
        if (!message) return null
        return (
          <div key={message?._id} className="flex items-center space-x-1 p-2">
            <h2>{message.author.name}</h2>
            <small className="">
              {convertUnixToTimestamp(message._creationTime)}
            </small>
            <p>{message.body}</p>
          </div>
        )
      })}
    </div>
  )
}


I'm only getting this error, and loosing my types - but other than that i get the messages with the authors and can display them as expected.
CleanShot_2023-11-13_at_23.07.26.gif
Was this page helpful?