summaryrefslogtreecommitdiffstats
path: root/frontend/src/Register.js
blob: c2d7e988a66e068fabf1ed81a223dc600d0655a0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
import React, { useState } from 'react';
import { useForm } from 'react-hook-form';
import { navigate } from '@reach/router';

import axios from './axios';
import userState from './UserState';

const Register = () => {
  const { register, handleSubmit } = useForm();
  const [ data, setData ] = useState({});

  const onSubmit = async data => {
    if (data.password !== data.confirm_password) {
      return setData({ errors: [ 'Passwords do not match.' ] });
    }
    try {
      const resp = await axios.post('/register', data);
      const { username } = resp.data;
      userState.authError = null;
      userState.username = username;
      setData({ submitted: true });
    } catch (err) {
      if (err.response && err.response.data) {
        setData({
          errors: [ err.response.data.error, ...(err.response.data.errors || []) ],
        });
      } else {
        console.error(err);
        setData({ errors: [ 'Unknown error occurred. See console for details.' ] });
      }
    }
  };

  if (data.submitted) {
    return <h1>You should be receiving an account activation email shortly.</h1>;
  }

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <h1 className="title">Register new account</h1>
      <label className="label">
        Username <input className="input" name="username" type="text" ref={register} required />
      </label>
      <label className="label">
        Email <input className="input" name="email" type="email" ref={register} required />
      </label>
      <label className="label">
        Password <input className="input" name="password" type="password" ref={register} required />
      </label>
      <label className="label">
        Confirm password <input className="input" name="confirm_password" type="password" ref={register} required />
      </label>
      <button className="button" type="submit">
        Register
      </button>
      <ul className="error">{data.errors ? data.errors.map(e => <li>{e}</li>) : null}</ul>
    </form>
  );
};

export default Register;