blob: 6eafd203ce7a9e792582dc32922b04e04e51c626 [file] [log] [blame]
arseniy.sorokinbdf2def2023-10-05 00:05:32 +02001import React, { Component } from 'react';
2import { Link, withRouter } from 'react-router-dom';
3import { Button, Container, Form, FormGroup, Input, Label } from 'reactstrap';
4import AppNavbar from './AppNavbar';
5
6class ClientEdit extends Component {
7
8 emptyItem = {
9 name: '',
10 email: ''
11 };
12
13 constructor(props) {
14 super(props);
15 this.state = {
16 item: this.emptyItem
17 };
18 this.handleChange = this.handleChange.bind(this);
19 this.handleSubmit = this.handleSubmit.bind(this);
20 }
21
22 async componentDidMount() {
23 if (this.props.match.params.id !== 'new') {
24 const client = await (await fetch(`/clients/${this.props.match.params.id}`)).json();
25 this.setState({item: client});
26 }
27 }
28
29 handleChange(event) {
30 const target = event.target;
31 const value = target.value;
32 const name = target.name;
33 let item = {...this.state.item};
34 item[name] = value;
35 this.setState({item});
36 }
37
38async handleSubmit(event) {
39 event.preventDefault();
40 const {item} = this.state;
41
42 await fetch('/clients' + (item.id ? '/' + item.id : ''), {
43 method: (item.id) ? 'PUT' : 'POST',
44 headers: {
45 'Accept': 'application/json',
46 'Content-Type': 'application/json'
47 },
48 body: JSON.stringify(item),
49 });
50 this.props.history.push('/clients');
51}
52
53 render() {
54 const {item} = this.state;
55 const title = <h2>{item.id ? 'Edit Client' : 'Add Client'}</h2>;
56
57 return <div>
58 <AppNavbar/>
59 <Container>
60 {title}
61 <Form onSubmit={this.handleSubmit}>
62 <FormGroup>
63 <Label for="name">Name</Label>
64 <Input type="text" name="name" id="name" value={item.name || ''}
65 onChange={this.handleChange} autoComplete="name"/>
66 </FormGroup>
67 <FormGroup>
68 <Label for="email">Email</Label>
69 <Input type="text" name="email" id="email" value={item.email || ''}
70 onChange={this.handleChange} autoComplete="email"/>
71 </FormGroup>
72 <FormGroup>
73 <Button color="primary" type="submit">Save</Button>{' '}
74 <Button color="secondary" tag={Link} to="/clients">Cancel</Button>
75 </FormGroup>
76 </Form>
77 </Container>
78 </div>
79 }
80}
81
82export default withRouter(ClientEdit);