From 7810cbaca1502586c1ef1a68a3d566d93434026c Mon Sep 17 00:00:00 2001 From: FrozenArcher Date: Tue, 12 Mar 2024 15:44:35 +0800 Subject: [PATCH] refactor request state --- src/service/index.ts | 20 ++++++++++++++++++++ src/service/ticketsInfo.ts | 19 ++++++------------- 2 files changed, 26 insertions(+), 13 deletions(-) diff --git a/src/service/index.ts b/src/service/index.ts index 24ab353..373362a 100644 --- a/src/service/index.ts +++ b/src/service/index.ts @@ -1,5 +1,15 @@ import process from 'process'; +/** + * State machine for request + * + * @example + * + * let former = this.state.rs; + * this.setState({ + * rs: former.trans(true), + * }) + */ export class RequestState { loading: boolean; success: boolean; @@ -7,6 +17,16 @@ export class RequestState { this.loading = true; this.success = false; } + + trans(success: boolean): RequestState { + if (this.loading) { + this.loading = false; + this.success = success; + } else { + console.error('calling trans on not loading state'); + } + return this; + } } /** diff --git a/src/service/ticketsInfo.ts b/src/service/ticketsInfo.ts index 554b4ab..a74edd7 100644 --- a/src/service/ticketsInfo.ts +++ b/src/service/ticketsInfo.ts @@ -13,12 +13,10 @@ export function getTicketInfo(that: TicketDetail, id: number) { }, }) .then(res => { + let former = that.state.rs; if (!res.data.success) { that.setState({ - rs: { - loading: false, - success: false, - }, + rs: former.trans(false), }); } else { const data = res.data.data; @@ -44,20 +42,15 @@ export function getTicketInfo(that: TicketDetail, id: number) { that.setState({ ticketInfo: ticketDetail, notes: notes, - rs: { - loading: false, - success: true, - }, + rs: former.trans(true), }); } }) .catch(reason => { + let former = that.state.rs; that.setState({ - rs: { - loading: false, - success: false, - }, + rs: former.trans(false), }); - console.log(reason); + console.error(reason); }); }