我有一个登录表单。当点击提交按钮时,我通过 GraphQL 后端检查电子邮件和密码是否正确。如果是,则返回 token 并将其存储在本地存储中。有时,会出现错误,例如:
“密码不正确”或“用户不存在”。
有没有办法将这些错误存储为字符串,以便我稍后可以使用条件渲染显示它们?
这就是我的突变的样子:
function submitForm(LoginMutation: any) {
const { email, password } = state;
if(email && password){
LoginMutation({
variables: {
email: email,
password: password,
},
}).then(({ data }: any) => {
localStorage.setItem('token', data.loginEmail.accessToken);
})
.catch(console.log)
}
}
我在返回中这样使用它
return (
<Mutation mutation={LoginMutation}>
{(LoginMutation: any) => (
....)}>
</Mutation>
)
目前,我只是根据 token 是否存在显示一个错误,但我想让我的错误特定于 GraphQL 错误。
function ShowError(){
if (!localStorage.getItem('token'))
{
console.log('Login Not Successful');
return <Typography color='primary'>Login Not Successful</Typography>
}
}
编辑:
错误示例:
[Log] Error: GraphQL error: Key (email)=(c@c.com) already exists.
我尝试过这个,但它从未记录任何内容:
.then(({data, errors}:any) => {
if (errors && errors.length) {
console.log('Errors', errors);
setErrorMessage(errors[0].message);
console.log('Whats the error', errors[0].message)
} else {
console.log('ID: ', data.createUser.id);
}
})
```
The backend isn't made by me
最佳答案
这取决于您如何设置一些东西,但是,假设您可以访问 ShowError
函数中的 state
:
使用 GraphQL 时,可能会通过两种方式发生错误:
1. 网络错误,将在.catch
中捕获。要处理此问题,在您的 catch
中,您可以将错误消息存储在状态中,然后从 ShowError
访问它:
...
.catch(err => {
setState({errorMessage: err.message});
});
- 作为错误查询的结果,通常会返回带有
errors
数组的成功响应。要处理这种情况,您可以在.then
中添加错误检查:
...
.then(({data, errors}) => {
if (errors && errors.length) {
setState({errorMessage: errors[0].message});
} else {
localStorage.setItem('token', data.loginEmail.accessToken);
}
});
关于javascript - 将 GraphQL 错误存储为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60578949/