-
Notifications
You must be signed in to change notification settings - Fork 36
/
Copy pathCustomerEdit.js
95 lines (85 loc) · 2.84 KB
/
CustomerEdit.js
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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
import React, { Component } from 'react';
import { Link, withRouter } from 'react-router-dom';
import { Button, Container, Form, FormGroup, Input, Label } from 'reactstrap';
import AppNavbar from './AppNavbar';
class CustomerEdit extends Component {
emptyCustomer = {
firstname: '',
lastname: '',
age: '',
address: '',
copyrigtby: ''
};
constructor(props) {
super(props);
this.state = {
item: this.emptyCustomer
};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
async componentDidMount() {
if (this.props.match.params.id !== 'new') {
const customer = await (await fetch(`/api/customer/${this.props.match.params.id}`)).json();
this.setState({item: customer});
}
}
handleChange(event) {
const target = event.target;
const value = target.value;
const name = target.name;
let item = {...this.state.item};
item[name] = value;
this.setState({item});
}
async handleSubmit(event) {
event.preventDefault();
const {item} = this.state;
await fetch('/api/customer', {
method: (item.id) ? 'PUT' : 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(item),
});
this.props.history.push('/customers');
}
render() {
const {item} = this.state;
const title = <h2>{item.id ? 'Edit Customer' : 'Add Customer'}</h2>;
return <div>
<AppNavbar/>
<Container>
{title}
<Form onSubmit={this.handleSubmit}>
<FormGroup>
<Label for="firstname">Firstname</Label>
<Input type="text" name="firstname" id="firstname" value={item.firstname || ''}
onChange={this.handleChange} autoComplete="firstname"/>
</FormGroup>
<FormGroup>
<Label for="lastname">Lastname</Label>
<Input type="text" name="lastname" id="lastname" value={item.lastname || ''}
onChange={this.handleChange} autoComplete="lastname"/>
</FormGroup>
<FormGroup>
<Label for="age">Age</Label>
<Input type="text" name="age" id="age" value={item.age || ''}
onChange={this.handleChange} autoComplete="age"/>
</FormGroup>
<FormGroup>
<Label for="address">Address</Label>
<Input type="text" name="address" id="address" value={item.address || ''}
onChange={this.handleChange} autoComplete="address"/>
</FormGroup>
<FormGroup>
<Button color="primary" type="submit">Save</Button>{' '}
<Button color="secondary" tag={Link} to="/customers">Cancel</Button>
</FormGroup>
</Form>
</Container>
</div>
}
}
export default withRouter(CustomerEdit);