DerPenz
DerPenz2y ago

How do I get an Id of a string

Is there some kind of Id Class
No description
14 Replies
Jamal
Jamal2y ago
ID class on what? on a table in your schema?
DerPenz
DerPenzOP2y ago
yeah
Jamal
Jamal2y ago
uh
DerPenz
DerPenzOP2y ago
the params.id will be highlighed red. it should acceppt a v.id('document')
Jamal
Jamal2y ago
oh okay where are you getting params.id from? url
DerPenz
DerPenzOP2y ago
yeah url
DerPenz
DerPenzOP2y ago
No description
DerPenz
DerPenzOP2y ago
it does not accept the id as string but a v.id() which is idk something else apparently
Jamal
Jamal2y ago
v.id is just a typeSafe way for the id to be called. You could convert the url parem.id from a string to _id have you tired to do it even with the error? because i think the ids are just strings under the hood
DerPenz
DerPenzOP2y ago
if I do params.id as Id<'document'> I will get an validator error thats my vscode error: Type 'string' is not assignable to type 'Id<"document">'. Type 'string' is not assignable to type '{ __tableName: "document"; }'.ts(2322)
Jamal
Jamal2y ago
but wait there must be a convert method for this lemme check the docs
DerPenz
DerPenzOP2y ago
Sure but I found nothing
Jamal
Jamal2y ago
maybe just cast it? as Id<document> ?
sshader
sshader2y ago
The thread here https://discord.com/channels/1019350475847499849/1141866166126649354 asks a similar question. There's not a way to tell if a string is an ID from the client, so you can either assume the string is an ID (and use v.id("myTable") which will throw when it's not, and myId as Id<"myTable"> to make TypeScript happy), or you can check if the string is a valid ID in a convex function and handle the case where it's not on the client Here's a snippet of what that second approach might look like:
const getGame = query({
args: { gameIdString: v.string()},
handler: async(ctx, { gameIdString }) => {
const gameId = ctx.db.normalizeId("game", gameIdString)

if (gameId === null) {
// Client can redirect to home page or similar
return { result: "Game not found" }
}
const game = await ctx.db.get(gameId);
// ...
}
})
const getGame = query({
args: { gameIdString: v.string()},
handler: async(ctx, { gameIdString }) => {
const gameId = ctx.db.normalizeId("game", gameIdString)

if (gameId === null) {
// Client can redirect to home page or similar
return { result: "Game not found" }
}
const game = await ctx.db.get(gameId);
// ...
}
})

Did you find this page helpful?