Skip to content

Commit

Permalink
Rewrite Form's onSubmit method to not use async/await [#153461036]
Browse files Browse the repository at this point in the history
  • Loading branch information
reidmit committed Dec 6, 2017
1 parent 5f694c2 commit c8e72e1
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 9 deletions.
2 changes: 1 addition & 1 deletion spec/pivotal-ui-react/form/form_spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -219,7 +219,7 @@ describe('Form', () => {
errors = {name: 'invalid'};
onSubmitError.and.returnValue(errors);
reject(error);
MockPromises.tick(1);
MockPromises.tick(2);
});

it('enables the top-level fieldset', () => {
Expand Down
34 changes: 26 additions & 8 deletions src/react/forms/form.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,10 @@ const deepClone = o => JSON.parse(JSON.stringify(o));
const noop = () => {
};

function isPromise(promise = {}) {
return typeof promise.then === 'function';
}

export class Form extends React.Component {
static propTypes = {
onModified: PropTypes.func.isRequired,
Expand Down Expand Up @@ -139,25 +143,39 @@ export class Form extends React.Component {
return !submitting && !deepEqual(initial, current);
}

async onSubmit(e) {
onSubmit(e) {
e && e.preventDefault();
const {onSubmit, onSubmitError, afterSubmit, onModified, resetOnSubmit} = this.props;
const {initial, current} = this.state;
this.setState({submitting: true});
const nextState = {submitting: false};
try {
const response = await onSubmit({initial, current});

const onSuccess = response => {
this.setState({
...nextState,
current: resetOnSubmit ? deepClone(initial) : current,
initial: resetOnSubmit ? initial : deepClone(current),
errors: {}
});
await onModified(false);
afterSubmit({state: this.state, setState: this.setState, response, reset: this.reset});
} catch (err) {
this.setState({...nextState, errors: (onSubmitError && onSubmitError(err)) || {}});
throw err;
const after = () => afterSubmit({state: this.state, setState: this.setState, response, reset: this.reset});
const onModifiedPromise = onModified(false);
return isPromise(onModifiedPromise) ? onModifiedPromise.then(after) : after();
};

const onError = e => {
this.setState({...nextState, errors: (onSubmitError && onSubmitError(e)) || {}});
};

const afterSubmitPromise = onSubmit({initial, current});
if (isPromise(afterSubmitPromise)) {
return afterSubmitPromise.then(onSuccess).catch(onError);
} else {
try {
return onSuccess(afterSubmitPromise);
} catch (e) {
onError(e);
throw e;
}
}
}

Expand Down

0 comments on commit c8e72e1

Please sign in to comment.