fix: update validation logic in useValidation hook and improve error handling in useLogin hook

This commit is contained in:
juan 2025-08-11 14:06:13 +02:00
parent a2ae7d5b5a
commit d4d384ba2b
6 changed files with 19 additions and 15 deletions

View File

@ -1,5 +1,5 @@
import { useState } from "react"
import type { z } from "zod"
import { z } from "zod"
type FormDataValidation = Record<string, FormDataEntryValue>
@ -26,7 +26,8 @@ export const useValidation = <T,>({
if (!result.success) {
//FIXME: Flatten errors, new in zod v4
setErrors(result.error.flatten().fieldErrors as T)
// setErrors(result.error.flatten().fieldErrors as T)
setErrors(z.flattenError(result.error).fieldErrors as T)
return false
}

View File

@ -15,10 +15,15 @@ export const useLogin = () => {
})
const loginMutation = useMutation({
mutationKey: ["login"],
mutationFn: async (data: TLoginForm) =>
loginUser({
mutationFn: async (data: TLoginForm) => {
const response = await loginUser({
data
}),
})
if (response.error) {
throw new Error(response.message)
}
},
onMutate: () => {
toast.loading("Logging in...", { id: "login" })
},
@ -28,8 +33,8 @@ export const useLogin = () => {
to: "/post"
})
},
onError: () => {
toast.error("Failed to log in.", { id: "login" })
onError: (error) => {
toast.error(error.message, { id: "login" })
}
})

View File

@ -1,12 +1,12 @@
import z from "zod"
export const loginFormSchema = z.object({
email: z.string("Invalid email address"),
email: z.email("Invalid email address"),
password: z.string().min(1, "Password must be at least 1 character long")
})
export const signupFormSchema = z.object({
email: z.string("Invalid email address"),
email: z.email("Invalid email address"),
password: z.string().min(6, "Password must be at least 6 characters long"),
redirectUrl: z.string().optional()
})

View File

@ -19,7 +19,7 @@ export const Route = createRootRouteWithContext<MyRouterContext>()({
beforeLoad: async () => {
const user = await getUser()
return {
user
...user
}
},
head: () => ({

View File

@ -1,10 +1,10 @@
import { createFileRoute } from "@tanstack/react-router"
import { createFileRoute, redirect } from "@tanstack/react-router"
export const Route = createFileRoute("/_authed")({
beforeLoad: ({ context }) => {
console.log("contextw", context)
if (!context?.user) {
if (context.error) {
throw new Error("Not authenticated")
// TODO: Redirect to login page
}
},
errorComponent: ({ error }) => {
@ -15,7 +15,6 @@ export const Route = createFileRoute("/_authed")({
</p>
)
}
throw error
}
})

View File

@ -12,7 +12,6 @@ function LoginComp() {
const handleSubmit = (e: FormEvent<HTMLFormElement>) => {
e.preventDefault()
const formData = new FormData(e.currentTarget)
login({