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

74 lines
1.8 KiB
TypeScript
Raw Permalink Normal View History

import React, { ReactNode } from 'react';
import { RouteComponentProps } from 'react-router-dom';
import AuthError from 'app/components/auth/authError/AuthError';
import { FormModel } from 'app/components/ui/form';
import Context, { AuthContext } from './Context';
/**
* Helps with form fields binding, form serialization and errors rendering
*/
class BaseAuthBody extends React.Component<
2020-05-24 04:38:24 +05:30
// TODO: this may be converted to generic type RouteComponentProps<T>
RouteComponentProps<Record<string, any>>
2019-12-07 16:58:52 +05:30
> {
2020-05-24 04:38:24 +05:30
static contextType = Context;
declare context: React.ContextType<typeof Context>;
2020-05-24 04:38:24 +05:30
prevErrors: AuthContext['auth']['error'];
2020-05-24 04:38:24 +05:30
autoFocusField: string | null = '';
2019-12-07 16:58:52 +05:30
2020-05-24 04:38:24 +05:30
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();
}
2020-05-24 04:38:24 +05:30
this.prevErrors = this.context.auth.error;
}
2020-05-24 04:38:24 +05:30
renderErrors(): ReactNode {
const error = this.form.getFirstError();
2020-05-24 04:38:24 +05:30
if (error === null) {
return null;
}
2019-12-07 16:58:52 +05:30
2020-05-24 04:38:24 +05:30
return <AuthError error={error} onClose={this.onClearErrors} />;
}
2020-05-24 04:38:24 +05:30
onFormSubmit() {
this.context.resolve(this.serialize());
}
2020-05-24 04:38:24 +05:30
onClearErrors = () => this.context.clearErrors();
2020-05-24 04:38:24 +05:30
form = new FormModel({
renderErrors: false,
});
2020-05-24 04:38:24 +05:30
bindField(name: string) {
return this.form.bindField(name);
}
2020-05-24 04:38:24 +05:30
serialize() {
return this.form.serialize();
}
2020-05-24 04:38:24 +05:30
autoFocus() {
const fieldId = this.autoFocusField;
2020-05-24 04:38:24 +05:30
if (fieldId && this.form.hasField(fieldId)) {
this.form.focus(fieldId);
}
}
}
export default BaseAuthBody;