Created
February 18, 2014 20:59
-
-
Save gaearon/9079957 to your computer and use it in GitHub Desktop.
Form Mixin for React (http://stackoverflow.com/q/21854938/458193)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
define(function () { | |
'use strict'; | |
var _ = require('underscore'); | |
var EDITABLE_STATE = 'editable', | |
SUBMITTING_STATE = 'submitting', | |
SUBMITTED_STATE = 'submitted'; | |
var FormMixin = { | |
getInitialState: function () { | |
return { | |
formState: EDITABLE_STATE | |
}; | |
}, | |
componentDidMount: function () { | |
if (!_.isFunction(this.sendRequest)) { | |
throw new Error('To use FormMixin, you must implement sendRequest.'); | |
} | |
}, | |
getFormState: function () { | |
return this.state.formState; | |
}, | |
setFormState: function (formState) { | |
this.setState({ | |
formState: formState | |
}); | |
}, | |
getFormError: function () { | |
return this.state.formError; | |
}, | |
setFormError: function (formError) { | |
this.setState({ | |
formError: formError | |
}); | |
}, | |
isFormEditable: function () { | |
return this.getFormState() === EDITABLE_STATE; | |
}, | |
isFormSubmitting: function () { | |
return this.getFormState() === SUBMITTING_STATE; | |
}, | |
isFormSubmitted: function () { | |
return this.getFormState() === SUBMITTED_STATE; | |
}, | |
submitForm: function () { | |
if (!this.isFormEditable()) { | |
throw new Error('Form can only be submitted when in editable state.'); | |
} | |
this.setFormState(SUBMITTING_STATE); | |
this.setFormError(undefined); | |
this.sendRequest() | |
.bind(this) | |
.then(function () { | |
this.setFormState(SUBMITTED_STATE); | |
}) | |
.catch(function (err) { | |
this.setFormState(EDITABLE_STATE); | |
this.setFormError(err); | |
}) | |
.done(); | |
} | |
}; | |
return FormMixin; | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I only used it for implementing form states (e.g. implement
sendRequest: Promise
, and you can disable buttons and fields based onisFormEditable()
).