如何处理useMutation
的错误,以使页面不会变成令人不快的Unhandled Rejection (Error)
?
尽管这篇帖子here描述了我的问题,但仍然无法解决。该帖子特别提及。 Instead of having to write the above boilerplate yourself, you can just use the provided result object.
是通过以下方式实现的:
const [signUp, { loading: mutationLoading, error: mutationError } [...]
但是,当发生错误时,我的React App总是切换到一个不好的“未处理的拒绝(错误):GraphQL错误”屏幕。 official doc似乎也可以使用类似的解决方案-但对我而言不是。
function SignUp() {
// Declare a new state variable, which we'll call "count"
const [login, setLogin] = useState(true);
const [username, setUsername] = useState("");
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [name, setName] = useState("");
const [
signUp,
{ loading: mutationLoading, error: mutationError }
] = useMutation(SIGNUP_MUTATION, {
onCompleted(data) {
const { token } = login ? data.tokenAuth : data.createUser;
localStorage.setItem(AUTH_TOKEN, token);
console.log(token);
// this.props.history.push(`/`);
}
});
return (
<div>
{mutationLoading && <p>Loading...</p>}
{mutationError && (
<p>
Some error occured :(
{console.log(mutationError)}
{mutationError.graphQLErrors.map(({ message }, i) => (
<span key={i}>{message}</span>
))}
</p>
)}
[...]
答案 0 :(得分:0)
const [
signUp,
{ loading: mutationLoading}
] = useMutation(SIGNUP_MUTATION, {
onCompleted(data) {
const { token } = login ? data.tokenAuth : data.createUser;
localStorage.setItem(AUTH_TOKEN, token);
console.log(token);
// this.props.history.push(`/`);
},
onError: (err) => {
setError(err);
// mutationError = err;
}
});