Skip to content

Instantly share code, notes, and snippets.

@kana-sama
Created October 18, 2019 11:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kana-sama/20974636eb0b07a8ec0491fc93dae3b3 to your computer and use it in GitHub Desktop.
Save kana-sama/20974636eb0b07a8ec0491fc93dae3b3 to your computer and use it in GitHub Desktop.
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