Skip to content

Instantly share code, notes, and snippets.

@bradfordlemley
Last active May 29, 2019 20:52
Show Gist options
  • Save bradfordlemley/e644152aa56521e68d02fd5e5d9ef613 to your computer and use it in GitHub Desktop.
Save bradfordlemley/e644152aa56521e68d02fd5e5d9ef613 to your computer and use it in GitHub Desktop.
Todo library with derived state
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