summaryrefslogtreecommitdiffstats
path: root/frontend/components/Signin.js
blob: 846fd0c8ec0be2e997f0bb7338c2a71a1327e11c (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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
import React, { Component } from 'react';
import { Mutation, Query } from 'react-apollo';
import { SIGNIN_MUTATION, CURRENT_USER_QUERY } from '../queries';
import Error from './ErrorMessage';
import Form from './styles/Form';

class Signin extends Component {
  state = {
    email: `wesbos@gmail.com`,
    password: 'abc123',
  };

  loginUser = async (e, signin, refetchUser) => {
    e.preventDefault();
    const res = await signin();
    localStorage.setItem('token', res.data.signin.token);
    await refetchUser();
    // TODO refetch current user query
  };

  update = (proxy, payload) => {
    console.log(proxy);
    const data = proxy.readQuery({ query: CURRENT_USER_QUERY });
    data.me = payload.data.signin.user;
    proxy.writeQuery({ query: CURRENT_USER_QUERY, data });
  };

  saveToState = e => {
    const { name, value } = e.target;
    this.setState({ [name]: value });
  };

  render() {
    // TODO / ASK - do I really have to wrap this in a query just to access the refetch function
    return (
      <Query query={CURRENT_USER_QUERY}>
        {({ refetch }) => (
          <Mutation mutation={SIGNIN_MUTATION} variables={this.state}>
            {(signin, { data, loading, error }) => (
              <Form onSubmit={e => this.loginUser(e, signin, refetch)}>
                <Error error={error} />
                <fieldset disabled={loading} aria-busy={loading}>
                  <label htmlFor="email">
                    Email
                    <input
                      value={this.state.email}
                      onChange={this.saveToState}
                      name="email"
                      type="text"
                      placeholder="email"
                    />
                  </label>

                  <label htmlFor="password">
                    Password
                    <input
                      type="password"
                      name="password"
                      id="password"
                      className="password"
                      placeholder="password"
                      value={this.state.password}
                      onChange={this.saveToState}
                    />
                  </label>

                  <button type="submit">Sign In!</button>
                </fieldset>
              </Form>
            )}
          </Mutation>
        )}
      </Query>
    );
  }
}

export default Signin;