user.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. import { Query, Mutation } from 'react-apollo'
  2. import Link from 'next/link'
  3. import { Formik, Form, Field, ErrorMessage } from 'formik'
  4. import { email } from '../lib/regex'
  5. import { adopt } from 'react-adopt'
  6. import { USER_LOGIN, CURRENT_USER } from '../lib/graphql'
  7. const UserLoginForm = props => <p>Login Form</p>
  8. const LoginAdoption = adopt({
  9. mutation: ({ render, formik }) => (
  10. <Mutation
  11. mutation={USER_LOGIN}
  12. refetchQueries={[{ query: CURRENT_USER }]}
  13. >{render}
  14. </Mutation>
  15. ),
  16. formik: ({ render, mutation }) => (
  17. <Formik
  18. initialValues={{ email: '', password: '' }}
  19. validate={values => {
  20. const errors = {}
  21. if (!values.email) errors.email = 'Required'
  22. else if (!email.test(values.email)) errors.email = 'Invalid email address'
  23. return errors
  24. }}
  25. onSubmit={(values, { setSubmitting }) => {
  26. mutation({ variables: values })
  27. }}
  28. >
  29. {render}
  30. </Formik>
  31. )
  32. })
  33. const LoginForm = props => (
  34. <LoginAdoption>
  35. {({ formik, mutation }) => {
  36. return (
  37. <Form>
  38. <Field type='email' name='email' />
  39. <ErrorMessage name='email' component='span' />
  40. <Field type='password' name='password' />
  41. <ErrorMessage name='password' component='span' />
  42. <button type='submit' disabled={formik.isSubmitting}>Login</button>
  43. </Form>
  44. )
  45. }}
  46. </LoginAdoption>
  47. )
  48. const UserNav = props => (
  49. <Query query={CURRENT_USER}>
  50. {
  51. ({ data, error, loading }) => {
  52. if (error) {
  53. return <LoginForm />
  54. }
  55. if (loading) return (<p>Loading...</p>)
  56. console.log(data)
  57. return (
  58. <Link href={{ pathname: 'user', query: { id: 12 } }}>
  59. <a>test {props.query}</a>
  60. </Link>
  61. )
  62. }
  63. }
  64. </Query>
  65. )
  66. const SignupForm = props => (
  67. <Formik
  68. initialValues={{ email: '', name: '', password: '', passwordAgain: '' }}
  69. onSubmit={values => {
  70. console.log('submitted', values)
  71. }}
  72. >
  73. {
  74. ({ isSubmitting }) => (
  75. <Form />
  76. )
  77. }
  78. </Formik>
  79. )
  80. const User = props => <a />
  81. export { UserNav }
  82. export default User