const options = {
baseURL: import.meta.env.VITE_API_URL,
withCredentials: true
}
const API = axios.create(options);
API.interceptors.response.use( function (response) {
return response.data;
}, function (error) {
const {status, data} = error.response;
return Promise.reject({status, ...data})
})
export default API;
type registerParams = {
email:string,
password:string,
confirmPassword:string
}
export const register = async (data: registerParams) => {
API.post("/auth/register", data)
}
register.tsx
const Register = () => {
const navigate = useNavigate()
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [confirmPassword, setConfirmPassword] = useState('');
const {
mutate: createAccount,
isPending,
isError,
error
} = useMutation({
mutationFn: register,
onSuccess: () => {
navigate('/', { replace: true })
}
})
return (
//Some-Code
<Box rounded='lg' bg='gray.700' boxShadow='lg' p={8}>
{
isError && (<Box mb={3} color='red.400'>
{
error?.message || "An error occured"
}
</Box>
)}
//Some-Code
<FormControl id='password'>
<FormLabel>Confirm Password</FormLabel>
<Input type='password'
value={confirmPassword}
onChange={(event) => setConfirmPassword(event.target.value)}
onKeyDown={
(event) => event.key === "Enter" && createAccount({ email:email, password:password, confirmPassword:confirmPassword })
}
/>
</FormControl>
<Button my={2} isDisabled={!email || password.length < 6 || password !== confirmPassword}
isLoading={isPending}
onClick={
() => createAccount({ email:email, password:password, confirmPassword:confirmPassword })
}
>Create Account</Button>
//Some-Code
}
export default Register
I可以确认在发送正确的输入时寄存器端点正在工作。
我试图向拒绝,承诺。解决和投掷错误和捕获的新承诺。我也尝试过utateasync。我曾期望突变的onsuccess()属性不起作用,而iserror是正确的,并且错误消息显示在
中
issue我怀疑问题是否因为您的
register
函数没有将任何内容返回回到mutationFn
register
被声明了。
async
由于
export const register = async (data: registerParams) => {
API.post("/auth/register", data) // <-- not returned
}
结果未返回,没有任何内容是
API.post
-deed,此await
函数立即返回,并且调用了回调处理程序。直到后来,任何API响应都被处理并可能被拒绝,但是通话代码已经返回,因此无关紧要。 sultionsusiond从查询突变函数返回
register
除非您实际上需要任何东西,否则返回诺言就足够了,因此您可以安全地删除onSuccess
声明
API.post
我不相信您需要明确创建/返回Axios Interceptors的任何承诺,您应该能够简单地返回错误有效负载,Axios处理请求承诺。
await