import {observable, autorun} from 'mobx'; import axios from 'axios'; import Post from '../models/postModel'; // TODO!! export default class BaseStore { @observable models = []; @observable isLoading = true; constructor(type, url) { this.type = type; this.url = url; } /** * Fetches all posts's from the server */ loadModels() { axios.get(this.url).then(fetchedModels => { fetchedModels.forEach(json => this.updateModelFromServer(json)); }); } /** * Update a post with information from the server. Guarantees a post * only exists once. Might either construct a new post, update an existing one, * or remove an post if it has been deleted on the server. */ updateModelFromServer(json) { var model = this.models.find(model => model.id === json.id); if (!model) { model = new Post(this, json.id); // TODO How to get the type of Class here?? this.models.push(model); } if (json.isDeleted) { this.removeModel(model); } else { post.updateFromJson(json); } } /** * Creates a fresh post on the client and server */ createModel() { var model = new Post(this); // TODO How to get the type of Class here?? this.models.push(model); return model; } /** * A post was somehow deleted, clean it from the client memory */ removeModel(model) { this.models.splice(this.models.indexOf(model), 1); model.dispose(); } }