Created
October 18, 2019 11:00
-
-
Save kana-sama/20974636eb0b07a8ec0491fc93dae3b3 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { observable, action, computed, flow } from "mobx"; | |
import { IHTTP } from "./http/interface"; | |
import { ConversationsItem } from "../types"; | |
class RemoteData<T> { | |
@observable public isLoaded: boolean = false; | |
@observable public isLoading: boolean = false; | |
@observable public isFailed: boolean = false; | |
@observable public dataValue: T | null = null; | |
@observable public error: any = undefined; | |
@computed get data() { | |
if (this.isLoaded && this.dataValue !== null) { | |
return this.dataValue; | |
} else { | |
throw new Error("check remote data before elimination"); | |
} | |
} | |
@computed | |
public get isUpdating(): boolean { | |
return this.isLoaded && this.isLoading; | |
} | |
@action | |
public load(promise: Promise<T>) { | |
this.isFailed = false; | |
this.isLoading = true; | |
promise.then( | |
action((result: T) => { | |
this.dataValue = result; | |
this.isLoading = false; | |
this.isLoaded = true; | |
}), | |
action((error: any) => { | |
this.isFailed = true; | |
this.error = error; | |
}) | |
); | |
} | |
} | |
export class CardsStore extends RemoteData<ConversationsItem[]> { | |
constructor(private http: IHTTP) { | |
super(); | |
} | |
@action | |
public get() { | |
this.load(this.http.get<ConversationsItem[]>("/items")); | |
} | |
@action | |
public async create(title: string) { | |
const item = await this.http.post<ConversationsItem>("/items", { title }); | |
if (this.isLoaded) this.data.push(item); | |
await this.get(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment