74c2600b46
* Fix api-routes-apollo-server-and-client-auth Example `client.resetStore()` must be called after SignIn, SignOut actions Otherwise, even the current basic auth is not working 100% of the time... For example, as caching occurs here: ``` const { data, loading } = useQuery(ViewerQuery) ``` it sometimes (race conditions!) prevents a user from signing in the current code base. Check https://github.com/apollographql/apollo-cache-persist/issues/34#issuecomment-371177206 comment for more info. * Fix api-routes-apollo-server-and-client-auth Example (linting)
77 lines
1.8 KiB
JavaScript
77 lines
1.8 KiB
JavaScript
import React from 'react'
|
|
import Link from 'next/link'
|
|
import { withApollo } from '../apollo/client'
|
|
import gql from 'graphql-tag'
|
|
import { useMutation, useApolloClient } from '@apollo/react-hooks'
|
|
import Field from '../components/field'
|
|
import { getErrorMessage } from '../lib/form'
|
|
import { useRouter } from 'next/router'
|
|
|
|
const SignInMutation = gql`
|
|
mutation SignInMutation($email: String!, $password: String!) {
|
|
signIn(input: { email: $email, password: $password }) {
|
|
user {
|
|
id
|
|
email
|
|
}
|
|
}
|
|
}
|
|
`
|
|
|
|
function SignIn() {
|
|
const client = useApolloClient()
|
|
const [signIn] = useMutation(SignInMutation)
|
|
const [errorMsg, setErrorMsg] = React.useState()
|
|
const router = useRouter()
|
|
|
|
async function handleSubmit(event) {
|
|
event.preventDefault()
|
|
|
|
const emailElement = event.currentTarget.elements.email
|
|
const passwordElement = event.currentTarget.elements.password
|
|
|
|
try {
|
|
const { data } = await signIn({
|
|
variables: {
|
|
email: emailElement.value,
|
|
password: passwordElement.value,
|
|
},
|
|
})
|
|
client.resetStore()
|
|
if (data.signIn.user) {
|
|
router.push('/')
|
|
}
|
|
} catch (error) {
|
|
setErrorMsg(getErrorMessage(error))
|
|
}
|
|
}
|
|
|
|
return (
|
|
<>
|
|
<h1>Sign In</h1>
|
|
<form onSubmit={handleSubmit}>
|
|
{errorMsg && <p>{errorMsg}</p>}
|
|
<Field
|
|
name="email"
|
|
type="email"
|
|
autoComplete="email"
|
|
required
|
|
label="Email"
|
|
/>
|
|
<Field
|
|
name="password"
|
|
type="password"
|
|
autoComplete="password"
|
|
required
|
|
label="Password"
|
|
/>
|
|
<button type="submit">Sign in</button> or{' '}
|
|
<Link href="signup">
|
|
<a>Sign up</a>
|
|
</Link>
|
|
</form>
|
|
</>
|
|
)
|
|
}
|
|
|
|
export default withApollo(SignIn)
|