accounts-frontend/packages/app/components/auth/BaseAuthBody.tsx

71 lines
1.8 KiB
TypeScript
Raw Normal View History

/**
* Helps with form fields binding, form serialization and errors rendering
*/
import PropTypes from 'prop-types';
2019-12-07 16:58:52 +05:30
import React from 'react';
import AuthError from 'app/components/auth/authError/AuthError';
import { userShape } from 'app/components/user/User';
import { FormModel } from 'app/components/ui/form';
2019-12-07 16:58:52 +05:30
import { RouteComponentProps } from 'react-router-dom';
2019-12-07 16:58:52 +05:30
export default class BaseAuthBody extends React.Component<
// TODO: this may be converted to generic type RouteComponentProps<T>
RouteComponentProps<{ [key: string]: any }>
> {
static contextTypes = {
clearErrors: PropTypes.func.isRequired,
resolve: PropTypes.func.isRequired,
requestRedraw: PropTypes.func.isRequired,
auth: PropTypes.shape({
error: PropTypes.oneOfType([
PropTypes.string,
PropTypes.shape({
type: PropTypes.string,
payload: PropTypes.object,
}),
]),
scopes: PropTypes.array,
}).isRequired,
user: userShape,
};
2019-12-07 16:58:52 +05:30
autoFocusField: string | null = '';
2019-12-10 13:17:32 +05:30
// eslint-disable-next-line react/no-deprecated
componentWillReceiveProps(nextProps, nextContext) {
if (nextContext.auth.error !== this.context.auth.error) {
this.form.setErrors(nextContext.auth.error || {});
}
}
renderErrors() {
2019-12-07 16:58:52 +05:30
const error = this.form.getFirstError();
return error && <AuthError error={error} onClose={this.onClearErrors} />;
}
2016-03-02 02:06:14 +05:30
onFormSubmit() {
this.context.resolve(this.serialize());
}
onClearErrors = this.context.clearErrors;
form = new FormModel({
renderErrors: false,
});
2019-12-08 03:23:22 +05:30
bindField(name: string) {
return this.form.bindField(name);
}
serialize() {
return this.form.serialize();
}
autoFocus() {
const fieldId = this.autoFocusField;
fieldId && this.form.focus(fieldId);
}
}