DerPenz
DerPenz16mo ago

How do I get an Id of a string

Is there some kind of Id Class
No description
14 Replies
CodingWithJamal
CodingWithJamal16mo ago
ID class on what? on a table in your schema?
DerPenz
DerPenzOP16mo ago
yeah
CodingWithJamal
CodingWithJamal16mo ago
uh
DerPenz
DerPenzOP16mo ago
the params.id will be highlighed red. it should acceppt a v.id('document')
CodingWithJamal
CodingWithJamal16mo ago
oh okay where are you getting params.id from? url
DerPenz
DerPenzOP16mo ago
yeah url
DerPenz
DerPenzOP16mo ago
No description
DerPenz
DerPenzOP16mo ago
it does not accept the id as string but a v.id() which is idk something else apparently
CodingWithJamal
CodingWithJamal16mo 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
DerPenzOP16mo 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)
CodingWithJamal
CodingWithJamal16mo ago
but wait there must be a convert method for this lemme check the docs
DerPenz
DerPenzOP16mo ago
Sure but I found nothing
CodingWithJamal
CodingWithJamal16mo ago
maybe just cast it? as Id<document> ?
sshader
sshader16mo 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?