formState.ts
· 807 B · TypeScript
Raw
export default abstract class FromState<T> {
data: T;
loading: boolean;
error: Error | null;
success: boolean;
constructor(data: T) {
this.data = data;
this.loading = false;
this.error = null;
this.success = false;
}
reset(): void {
this.loading = false;
this.error = null;
this.success = false;
}
async submit(): Promise<void> {
this.loading = true;
this.error = null;
try {
await this.post();
this.success = true;
} catch (error: any) {
console.error("Error while submitting form", error);
this.success = false;
if (error instanceof Error)
this.error = error;
this.handleError();
}
this.loading = false;
}
abstract post(): Promise<void>;
handleError(): Promise<void> | void { };
}
| 1 | export default abstract class FromState<T> { |
| 2 | data: T; |
| 3 | loading: boolean; |
| 4 | error: Error | null; |
| 5 | success: boolean; |
| 6 | |
| 7 | constructor(data: T) { |
| 8 | this.data = data; |
| 9 | this.loading = false; |
| 10 | this.error = null; |
| 11 | this.success = false; |
| 12 | } |
| 13 | |
| 14 | reset(): void { |
| 15 | this.loading = false; |
| 16 | this.error = null; |
| 17 | this.success = false; |
| 18 | } |
| 19 | |
| 20 | async submit(): Promise<void> { |
| 21 | this.loading = true; |
| 22 | this.error = null; |
| 23 | try { |
| 24 | await this.post(); |
| 25 | this.success = true; |
| 26 | } catch (error: any) { |
| 27 | console.error("Error while submitting form", error); |
| 28 | this.success = false; |
| 29 | if (error instanceof Error) |
| 30 | this.error = error; |
| 31 | this.handleError(); |
| 32 | } |
| 33 | this.loading = false; |
| 34 | } |
| 35 | |
| 36 | abstract post(): Promise<void>; |
| 37 | handleError(): Promise<void> | void { }; |
| 38 | } |
| 39 |