|
| 1 | +import React from 'react'; |
| 2 | +import Formsy from 'formsy-react'; |
| 3 | +import { Input } from 'formsy-react-components'; |
| 4 | +import { fakeData } from '../data/fakeData.js'; |
| 5 | + |
| 6 | +export class PersonEditor extends React.Component { |
| 7 | + constructor() { |
| 8 | + super(); |
| 9 | + this.state = { savedChanges: false }; |
| 10 | + } |
| 11 | + |
| 12 | + onChange() { |
| 13 | + this.setState({ savedChanges: false }); |
| 14 | + } |
| 15 | + |
| 16 | + submit(model, reset, setErrors) { |
| 17 | + PersonEditor.sendJson('put', `/api/people/${ this.props.params.personId }`, model).then(response => { |
| 18 | + if (response.ok) { |
| 19 | + this.setState({ savedChanges: true }); |
| 20 | + } else { |
| 21 | + // Parse server-side validation errors from the response and display them |
| 22 | + response.json().then(setErrors); |
| 23 | + } |
| 24 | + }); |
| 25 | + } |
| 26 | + |
| 27 | + render() { |
| 28 | + var personId = parseInt(this.props.params.personId); |
| 29 | + var person = fakeData.filter(p => p.id === personId)[0]; |
| 30 | + var notificationBox = this.state.savedChanges |
| 31 | + && <div className="alert alert-success"><b>Done!</b> Your changes were saved.</div>; |
| 32 | + |
| 33 | + return <div className='row'> |
| 34 | + <div className='page-header'> |
| 35 | + <h1>Edit { person.name }</h1> |
| 36 | + </div> |
| 37 | + <Formsy.Form ref='form' className='form-horizontal' onChange={ this.onChange.bind(this) } onValidSubmit={ this.submit.bind(this) }> |
| 38 | + <Input name='name' label='Name' value={ person.name } required /> |
| 39 | + <Input name='city' label='City' value={ person.city } required /> |
| 40 | + <Input name='state' label='State' value={ person.state } required /> |
| 41 | + <Input name='country' label='Country' value={ person.country } required /> |
| 42 | + <Input name='company' label='Company' value={ person.company } required /> |
| 43 | + <Input name='favoriteNumber' label='Favorite Number' value={ person.favoriteNumber } required validations="isInt" validationError="Must be a number" /> |
| 44 | + { notificationBox } |
| 45 | + <button type='submit' className='btn btn-primary'>Save</button> |
| 46 | + </Formsy.Form> |
| 47 | + </div>; |
| 48 | + } |
| 49 | + |
| 50 | + static sendJson(method, url, object) { |
| 51 | + return fetch(url, { |
| 52 | + method: method, |
| 53 | + headers: { 'Content-Type': 'application/json' }, |
| 54 | + body: JSON.stringify(object) |
| 55 | + }); |
| 56 | + } |
| 57 | +} |
0 commit comments