Todo + React + Mobx
Render ajax request/response with Mobx+React
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.5.4/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.5.4/react-dom.min.js"></script>
<script src="https://unpkg.com/[email protected]"></script>
<script src="https://unpkg.com/mobx@3/lib/mobx.umd.js"></script>
<script src="https://unpkg.com/mobx-react@4"></script>
<script src="https://unpkg.com/mobx-utils/mobx-utils.umd.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-compat/3.0.0-alpha1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.2.10/semantic.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.2.10/semantic.min.css">
<div id="root"></div>
Babel + JSX
const {observable, when, action} = mobx;
const {fromPromise, PENDING, REJECTED, FULFILLED}= mobxUtils;
const {Provider, observer, inject} = mobxReact;
const TODO_ENDPOINT = '/echo/json/';
class Todo {
@observable title;
@observable completed = false;
constructor(title, id = Math.random()) {
this.title = title;
this.id = id;
}
}
class TodoStore {
@observable todos = [];
@action fetchTodos = () => fromPromise(
fetch(TODO_ENDPOINT, { method: "GET" })
.then(resp => this.todos.replace(resp))
);
@action addTodo = (title) => {
const todo = new Todo(title);
var body = new FormData();
body.append("json", JSON.stringify(todo));
body.append("delay", JSON.stringify(0));
return fromPromise(
fetch(TODO_ENDPOINT, { method: "POST", body })
.then(res => res.json())
.then(resp => this.todos.push(resp))
);
}
@action complete = (todoId, shouldComplete=true) => {
var body = new FormData();
body.append("json", JSON.stringify({ id: todoId, complete: shouldComplete }));
body.append("delay", JSON.stringify(0));
return fromPromise(
fetch(TODO_ENDPOINT, { method: "POST", body })
.then(resp => resp.json())
.then((todoResp) => {
const todo = this.todos.find(t => t.id === todoResp.id);
todo.complete = todoResp.complete;
return todo;
})
);
}
}
@inject('todoStore') @observer
class TodoView extends React.Component {
constructor(props) {
super(props);
this.setCompleted = this.setCompleted.bind(this);
this.state = {isLoading: false};
}
componentDidMount() {
const { todo } = this.props;
const self = this;
const $checkbox = $(this.checkInput)
$checkbox.checkbox({
onChange: function() {
self.setCompleted(this.checked)
}
});
todo.complete
? $checkbox.checkbox('check')
:...