Skip to content

Instantly share code, notes, and snippets.

@otbe
Last active May 1, 2016 17:34
Show Gist options
  • Select an option

  • Save otbe/50e3bdfbba2cf0cd1c7fe21008298c15 to your computer and use it in GitHub Desktop.

Select an option

Save otbe/50e3bdfbba2cf0cd1c7fe21008298c15 to your computer and use it in GitHub Desktop.
import { map } from 'mobx/lib/mobx';
interface Todo {
id: string;
name: string;
active: boolean;
}
export class MyTodoStore {
todos = map<Todo>();
async loadTodos (): Promise<void> {
let todos: Array<Todo> = await fetchTodos());
transaction(() => {
this.todos.clear();
for (let todo of todos) {
this.todos.set(todo.id, todo);
}
});
}
async loadTodo (todoId: string): Promise<void> {
try {
const todo: Todo = await fetchTodo(todoId);
this.todos.set(todoId, todo);
} catch (e) {
throw new Error('Todo not found.');
}
}
}
import React, { Component } from 'react';
import { observer } from 'mobx-react/index';
import { observable } from 'mobx/lib/mobx';
@observer
export class Todo extends Component<{todoId: string, store: MyTodoStore}, {}> {
@observable
private todoId: string;
@computed
private get todo (): Todo {
return this.props.store.todos.get(this.todoId);
}
async componentWillMount () {
const { todoId, store } = this.props;
this.todoId = todoId;
await this.loadTodo(todoId);
}
render() {
if(this.todo != null) {
return <p>{todo.name}</p>
}
return null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment