- 移除 useGameBoardVm 数据层实施说明文档 - 移除核心玩法与前端规则摘要文档 - 移除游戏模块数据与界面分层第一阶段实施稿文档 - 清理与数据层重构相关的技术方案说明 - 删除关于 PC 和 Mobile 界面分离的设计规划 - 移除 view-model hooks 架构设计相关内容
71 lines
2.0 KiB
TypeScript
71 lines
2.0 KiB
TypeScript
import { useMutation } from '@tanstack/react-query'
|
|
import { useForm } from 'react-hook-form'
|
|
import { registerWithPassword } from '@/api'
|
|
import {
|
|
DEFAULT_REGISTER_INVITE_CODE,
|
|
REGISTER_INVITE_CODE_QUERY_PARAM,
|
|
} from '@/constants'
|
|
import i18n from '@/i18n'
|
|
import { notify } from '@/lib/notify'
|
|
import {
|
|
type RegisterFormValues,
|
|
registerFormSchema,
|
|
} from '@/schema/auth-schema'
|
|
import { useAuthStore } from '@/store/auth'
|
|
import type { UseRegisterFormOptions } from '@/type'
|
|
import { toAuthSubmitErrorKey } from './auth-error-key'
|
|
import { createZodResolver } from './zod-form-resolver'
|
|
|
|
function getInitialRegisterInviteCode() {
|
|
if (typeof window === 'undefined') {
|
|
return DEFAULT_REGISTER_INVITE_CODE
|
|
}
|
|
|
|
return (
|
|
new URLSearchParams(window.location.search)
|
|
.get(REGISTER_INVITE_CODE_QUERY_PARAM)
|
|
?.trim() || DEFAULT_REGISTER_INVITE_CODE
|
|
)
|
|
}
|
|
|
|
export function useRegisterForm({ onSuccess }: UseRegisterFormOptions = {}) {
|
|
const startSession = useAuthStore((state) => state.startSession)
|
|
const form = useForm<RegisterFormValues>({
|
|
defaultValues: {
|
|
captcha: '',
|
|
confirmPassword: '',
|
|
inviteCode: getInitialRegisterInviteCode(),
|
|
mobile: '',
|
|
password: '',
|
|
},
|
|
mode: 'onBlur',
|
|
resolver: createZodResolver(registerFormSchema),
|
|
})
|
|
const mutation = useMutation({
|
|
mutationFn: (values: RegisterFormValues) => {
|
|
const { confirmPassword: _confirmPassword, ...payload } = values
|
|
|
|
return registerWithPassword(payload)
|
|
},
|
|
onError: (error) => {
|
|
const errorKey = toAuthSubmitErrorKey(error, 'register')
|
|
|
|
if (errorKey) {
|
|
notify.error(i18n.t(errorKey))
|
|
}
|
|
},
|
|
onSuccess: (session) => {
|
|
startSession(session)
|
|
notify.success(i18n.t('commonUi.toast.registerSuccess'))
|
|
onSuccess?.()
|
|
},
|
|
})
|
|
|
|
return {
|
|
form,
|
|
isSubmitting: mutation.isPending,
|
|
onSubmit: form.handleSubmit((values) => mutation.mutateAsync(values)),
|
|
submitError: toAuthSubmitErrorKey(mutation.error, 'register'),
|
|
}
|
|
}
|