Created
February 11, 2019 08:12
-
-
Save TimoWestland/dee2668112a5465b10f81398570efc15 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 { action, computed, observable, reaction } from 'mobx' | |
export interface Todo { | |
task: string | |
isComplete: boolean | |
} | |
export class TodoStore { | |
@observable public todoList: Todo[] = [] | |
public constructor() { | |
reaction( | |
() => this.todoList.filter(todo => !todo.isComplete), | |
incompleteTasks => { | |
if (incompleteTasks.length > 15) { | |
alert("Dude, you've got too much on your plate. Let's get to it.") | |
} | |
}, | |
) | |
} | |
@computed | |
public get completedTodos(): Todo[] { | |
return this.todoList.filter(todo => todo.isComplete) | |
} | |
@computed | |
public get incompleteTodos(): Todo[] { | |
return this.todoList.filter(todo => !todo.isComplete) | |
} | |
@action | |
public addTodo(task: string) { | |
this.todoList.push({ task, isComplete: false }) | |
this.sortTodoList() | |
this.storeToLocal() | |
} | |
@action | |
public completeTodo(completedTodo: Todo) { | |
const i = this.todoList.findIndex(todo => todo.task === completedTodo.task) | |
this.todoList[i].isComplete = true | |
this.sortTodoList() | |
this.storeToLocal() | |
} | |
@action | |
public clearTodos() { | |
this.todoList = [] | |
} | |
private sortTodoList() { | |
const sorted = this.todoList | |
.slice() | |
.sort((a, b) => Number(a.isComplete) - Number(b.isComplete)) | |
this.todoList = [...sorted] | |
} | |
private storeToLocal() { | |
return window.localStorage.setItem( | |
'todos', | |
JSON.stringify(this.todoList || []), | |
) | |
} | |
private getFromLocal() { | |
return JSON.parse(window.localStorage.getItem('todos') || '{}') | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment