Last active
May 29, 2019 20:52
-
-
Save bradfordlemley/e644152aa56521e68d02fd5e5d9ef613 to your computer and use it in GitHub Desktop.
Todo library with derived state
This file contains 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 { createSelector } from 'reselect'; | |
import createBase from './StatedLibBase'; | |
export default function createTodoLib() { | |
const getCompletedTodos = createSelector( | |
state => state.todos, | |
todos => todos.filter(todo => todo.completed), | |
); | |
const getActiveTodos = createSelector( | |
state => state.todos, | |
todos => todos.filter(todo => !todo.completed), | |
); | |
function deriveState(state) { | |
return { | |
...state, | |
get completedTodos() { return getCompletedTodos(state) }, | |
get activeTodos() { return getActiveTodos(state) }, | |
}; | |
} | |
const base = createBase({ todos: [], isFetching: false }, deriveState); | |
const {updateState, state$} = base; | |
return { | |
get state: {return base.state}, | |
state$, | |
addTodo(title) { | |
updateState({ todos: base.state.todos.concat({ title, completed: false }) }); | |
}, | |
async fetchTodos() { | |
updateState({ isFetching: true }); | |
const newTodos = await fetchFromCloud(); | |
updateState({ | |
isFetching: false, | |
todos: base.state.todos.concat(newTodos), | |
}); | |
}, | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment