import React, { Component } from 'react'; import { Link, Redirect } from 'react-router-dom'; import ErrorBox from './error-box'; import InfoBox from './info-box'; import Sidebar from './sidebar'; class BuildingEdit extends Component { constructor(props) { super(props); const user = props.user || {}; this.state = { error: undefined, id: props.id, geometry_id: props.geometry_id, location_name: props.location_name, location_number: props.location_number, location_line_two: props.location_line_two, location_street: props.location_street, location_postcode: props.location_postcode, date_year: props.date_year, date_lower: props.date_lower, date_upper: props.date_upper, date_source: props.date_source, date_facade: props.date_facade, size_attic: props.size_attic, size_core: props.size_core, size_basement: props.size_basement, likes: props.likes || [], liked: this.user_likes(user.id, props.likes) }; this.handleChange = this.handleChange.bind(this); this.handleLike = this.handleLike.bind(this); this.handleSubmit = this.handleSubmit.bind(this); } user_likes(user_id, likes) { return likes && likes.indexOf(user_id) !== -1; } handleChange(event) { const target = event.target; const value = target.value; const name = target.name; this.setState({ [name]: value }); } handleLike(event) { const liked = event.target.checked; const likes = this.state.likes || []; if (liked) { this.setState({ likes: likes.concat([this.props.user.id]), liked: true }); } else { this.setState({ likes: likes.filter(id => id !== this.props.user.id), liked: false }); } } handleSubmit(event) { event.preventDefault(); this.setState({error: undefined}) fetch(`/building/${this.props.id}.json`, { method: 'POST', body: JSON.stringify(this.state), headers:{ 'Content-Type': 'application/json' } }).then( res => res.json() ).then(function(res){ if (res.error) { this.setState({error: res.error}) } else { this.props.selectBuilding(this.state); // could use server response? this.props.history.push(`/building/${this.state.id}.html`); } }.bind(this)).catch( (err) => this.setState({error: err}) ); } render() { if (!this.props.user){ return } if (!this.props.id){ return ( Back to maps ); } return ( Location Building name Building number Street Address line 2 Town Postcode Age Year built (best estimate) Year built (upper estimate) Year built (lower estimate) Facade date Source Size Attic storeys Core storeys Basement storeys Like Me! Like this building? Cancel Save ); } } export default BuildingEdit;