我正在尝试使用React和Apollo创建一个用户身份验证页面。我得到以下代码的onClick
事件的事件未定义:
const Auth = props => {
const [email, setEmail] = useState('')
const [password, setPassword] = useState('')
const onSubmitHandler = async (login, e) => {
e.preventDefault()
const authResults = await login()
props.history.push('/')
}
return (
<Mutation
mutation={LOGIN}
variables={{ email, password }}
>
{(login, {data, error, loading}) => {
if(loading) return <div>...loading</div>
if(error) return <div>Error</div>
return (
<form onSubmit={onSubmitHandler}>
<fieldset>
<label htmlFor="email">
Email
</label>
<input
type="email"
id="email"
value={email}
onChange={e => {
setEmail(e.target.value)
}}
/>
</fieldset>
<fieldset>
<label htmlFor="password">
Password
</label>
<input
type="password"
id="password"
value={password}
onChange={e => {
setPassword(e.target.value)
}}
/>
</fieldset>
<button>Login</button>
</form>
)
}}
</Mutation>
)
我尝试在调用时包括以下变量:
<form onSubmit={(login, e) => onSubmitHandler(login, e)}>
但是,无济于事。
编辑:最初的问题已解决,但是当我重构代码以利用react-apollo-hooks时,我不断遇到以下错误:
Variable "$email" of required type "String!" was not provided
Variable "$password" of required type "String!" was not provided
我的重构代码如下:
const [email, setEmail] = useState('')
const [password, setPassword] = useState('')
const variables = {
data: { email, password }
}
const login = useMutation(LOGIN_MUTATION, {
variables
})
const onSubmitHandler = async (login, e) => {
e.preventDefault()
const authResults = await login()
localStorage.setItem(AUTH_TOKEN, authResults.data.login.token);
props.history.push('/')
}
graphql突变
const LOGIN_MUTATION = gql`
mutation Login($email: String!, $password: String!) {
login(data: {
email: $email, password: $password
}
){
token
user {
id
}
}
}
`
我的模式
登录(数据:LoginUserInput!):AuthPayload!