import React from 'react'; import EditionActions from '../actions/edition_actions' import AppConstants from '../constants/application_constants' import AlertDismissable from '../components/ascribe_forms/alert' export const FormMixin = { getInitialState() { return { submitted: false , status: null , errors: [] } }, submit(e) { e.preventDefault(); for (var ref in this.refs){ this.refs[ref].clearAlerts(); } this.setState({submitted: true, errors: []}); fetch(this.url(), { method: 'post', headers: { 'Authorization': 'Basic ' + AppConstants.debugCredentialBase64, 'Accept': 'application/json', 'Content-Type': 'application/json' }, body: JSON.stringify(this.getFormData()) }) .then( (response) => this.handleResponse(response) ); }, handleResponse(response){ let submitted = false; if (response.status >= 200 && response.status < 300){ EditionActions.fetchOne(this.props.edition.id); this.props.onRequestHide(); submitted = true; } else if (response.status >= 400 && response.status < 500) { this.handleError(response); } this.setState({submitted: submitted, status: response.status}); }, handleError(response){ response.json().then((response) => this.dispatchErrors(response.errors)); }, dispatchErrors(errors){ for (var input in errors){ if (this.refs && this.refs[input] && this.refs[input].state){ this.refs[input].setAlerts(errors[input]); } else{ this.setState({errors: this.state.errors.concat(errors[input])}); } } }, render(){ let alert = null; if (this.state.status >= 500){ alert = ; } if (this.state.errors.length > 0){ alert = this.state.errors.map( function(error) { return ; }.bind(this) ); } return ( {alert} {this.renderForm()} ) } }; export default FormMixin;