You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
42 lines
863 B
TypeScript
42 lines
863 B
TypeScript
import { z } from 'zod'
|
|
|
|
const userSchema = z.object({
|
|
email: z.string().email(),
|
|
password: z.string().min(6),
|
|
})
|
|
|
|
const userLogin = async (email: String, password: String) => {
|
|
await getUser()
|
|
if (useUser().value) return
|
|
|
|
const user = userSchema.safeParse({ email, password })
|
|
|
|
if (!user.success) return user.error.format()
|
|
|
|
await request.get('/sanctum/csrf-cookie')
|
|
await request.post('/login', user.data)
|
|
|
|
await getUser()
|
|
}
|
|
|
|
const getUser = async () => {
|
|
await request
|
|
.get('/api/user')
|
|
.then(({ data }) => {
|
|
const parsed = loggedInUserSchema.safeParse(data)
|
|
if (!parsed.success) return
|
|
useUser().value = parsed.data.name
|
|
})
|
|
.catch((error) => {
|
|
console.log(error)
|
|
})
|
|
}
|
|
|
|
const loggedInUserSchema = z.object({
|
|
name: z.string(),
|
|
})
|
|
|
|
const useUser = () => useState<String>('user', () => '')
|
|
|
|
export { userLogin, useUser, getUser }
|