summaryrefslogtreecommitdiffstats
path: root/frontend/components/EditUser.js
blob: b885fe6035377d4d5b9a0481a8fc121cfebd6248 (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
import React from 'react';
import { compose } from 'react-apollo';
import PropTypes from 'prop-types';
import Form from './styles/Form';
import { userEnhancer, updateUserEnhancer } from '../enhancers/enhancers';

class EditUser extends React.Component {
  static propTypes = {
    currentUser: PropTypes.object.isRequired,
    updateUser: PropTypes.func.isRequired,
  };

  state = {
    changes: {},
  };

  handleChange = e => {
    const { name, value } = e.target;
    const { me } = this.props.currentUser;
    const changes = {
      ...this.state.changes,
      [name]: value,
    };
    if (value === me[e.target.name]) {
      delete changes[name];
    }
    this.setState({ changes });
  };

  handleSubmit = async e => {
    e.preventDefault();
    await this.props.updateUser({
      variables: this.state.changes,
    });
    this.props.currentUser.refetch();
    this.setState({ changes: {} });
  };

  render() {
    const { me } = this.props.currentUser;
    if (!me) return <p>You must be logged in</p>;
    return (
      <Form onSubmit={this.handleSubmit}>
        <label htmlFor="name">
          Name:
          <input type="text" name="name" defaultValue={me.name} onChange={this.handleChange} />
        </label>
        <button type="submit">Update</button>
        <strong>me:</strong>
        <pre>{JSON.stringify(me.name)}</pre>
        <strong>Change:</strong>
        <pre data-test="change">{JSON.stringify(this.state.changes)}</pre>
      </Form>
    );
  }
}

export default compose(userEnhancer, updateUserEnhancer)(EditUser);
export { EditUser };