@@ -0,0 +1,73 @@
1+import React from 'react';
2+import { Button, Form, FormGroup, Input, Label } from 'reactstrap';
3+import axios from 'axios';
4+import { API_URL } from '../constants';
5+
6+
7+class UserForm extends React.Component {
8+ state = {
9+ id: 0,
10+ username: '',
11+ caloriesPerDay: 0
12+ };
13+
14+ componentDidMount() {
15+ if (this.props.user) {
16+ const { id, username, caloriesPerDay } = this.props.user;
17+ this.setState({ id, username, caloriesPerDay });
18+ }
19+ }
20+
21+ onChange = e => {
22+ this.setState({ [e.target.name]: e.target.value });
23+ };
24+
25+ createUser = e => {
26+ e.preventDefault();
27+ axios.post(API_URL + 'users', this.state).then(() => {
28+ this.props.resetState();
29+ this.props.toggle();
30+ });
31+ };
32+
33+ editUser = e => {
34+ e.preventDefault();
35+ axios.put(API_URL + 'users/' + this.state.id, this.state).then(() => {
36+ this.props.resetState();
37+ this.props.toggle();
38+ });
39+ };
40+
41+ defaultIfEmpty = value => {
42+ return value === "" ? "" : value;
43+ };
44+
45+ render() {
46+ return (
47+ <Form onSubmit={this.props.user ? this.editUser : this.createUser}>
48+ <FormGroup>
49+ <Label for="username">username:</Label>
50+ <Input
51+ type="text"
52+ name="username"
53+ onChange={this.onChange}
54+ value={this.defaultIfEmpty(this.state.name)}
55+ />
56+ </FormGroup>
57+ <FormGroup>
58+ <Label for="caloriesPerDay">Calories per day:</Label>
59+ <Input
60+ type="text"
61+ name="caloriesPerDay"
62+ onChange={this.onChange}
63+ value={this.defaultIfEmpty(this.state.name)}
64+ />
65+ </FormGroup>
66+
67+ <Button>Save</Button>
68+ </Form>
69+ )
70+ }
71+}
72+
73+export default UserForm;