how to handle tRPC errors with mutationAsync on my react frontend?

im trying to convert this component to use tRPC mutation https://pastebin.com/4sJKCULW here is what I have so far https://pastebin.com/6Hph40Ur this is the backend route
createUser:
t.procedure
.input(
z.object({
username: z.string(),
password: z.string()
})
)
.mutation(async (opts) => {
const { input } = opts
const user = await prisma.user.create({ data: input })
return user
}),
createUser:
t.procedure
.input(
z.object({
username: z.string(),
password: z.string()
})
)
.mutation(async (opts) => {
const { input } = opts
const user = await prisma.user.create({ data: input })
return user
}),
I am not getting consistent errors, for example in the screenshots u can see a prisma unique constraint and a zod error from the backend, they both have different structures unfortunately to get the message from the zod, I have to JSON.parse and then do something like message[0].message which doesnt seem intuitive so how would I handle errors in my try catch ? also what type do I give the error block?
} catch (error: any) {
console.log("<> <> <> ERROR CAUGHT <> <> <> : ", typeof error, Array.isArray(error))
console.log(error)
setCreateFormInfo("error caught: " + error.message)
}
} catch (error: any) {
console.log("<> <> <> ERROR CAUGHT <> <> <> : ", typeof error, Array.isArray(error))
console.log(error)
setCreateFormInfo("error caught: " + error.message)
}
also while im here, how do i get the zod validation from backend to do frontend validation as well before sending fetch? and also doing const data = await res feels wrong to me any tips appreciated in converting this very simple component, thanks
Pastebin
import { useState } from 'react'import { BASE_URL } from '..'interf...
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Pastebin
import { useState } from 'react'import { RouterInputs, trpc } from ...
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
3 Replies
Neto
Neto13mo ago
you can use the mutate and not the mutateAsync to gracefully handle errors allowing you to access via f_createUser.isError and f_createUser.error for form validation using zod you can use react-hook-form
Neto
Neto13mo ago
GitHub
GitHub - react-hook-form/resolvers: 📋 Validation resolvers: Yup, Zo...
📋 Validation resolvers: Yup, Zod, AJV, Joi, Superstruct, Vest, class-validator, io-ts, typanion, Ajv, TypeBox and nope. - GitHub - react-hook-form/resolvers: 📋 Validation resolvers: Yup, Zod, AJV, ...
Neto
Neto13mo ago
the Expected string, received number is self explanatory, somewhere you sent password as a string