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

69 lines
1.6 KiB
TypeScript
Raw Normal View History

2019-12-07 16:58:52 +05:30
import React from 'react';
import AuthError from 'app/components/auth/authError/AuthError';
import { FormModel } from 'app/components/ui/form';
2019-12-07 16:58:52 +05:30
import { RouteComponentProps } from 'react-router-dom';
import Context, { AuthContext } from './Context';
/**
* Helps with form fields binding, form serialization and errors rendering
*/
class BaseAuthBody extends React.Component<
2019-12-07 16:58:52 +05:30
// TODO: this may be converted to generic type RouteComponentProps<T>
RouteComponentProps<{ [key: string]: any }>
> {
static contextType = Context;
/* TODO: use declare */ context: React.ContextType<typeof Context>;
prevErrors: AuthContext['auth']['error'];
2019-12-07 16:58:52 +05:30
autoFocusField: string | null = '';
componentDidMount() {
this.prevErrors = this.context.auth.error;
}
componentDidUpdate() {
if (this.context.auth.error !== this.prevErrors) {
this.form.setErrors(this.context.auth.error || {});
this.context.requestRedraw();
}
this.prevErrors = this.context.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;
if (fieldId && this.form.hasField(fieldId)) {
this.form.focus(fieldId);
}
}
}
export default BaseAuthBody;