Skip to content

Instantly share code, notes, and snippets.

@cevr
Created June 8, 2019 22:01
Show Gist options
  • Save cevr/88e89c06be83a098edb337fbfdc7c1f1 to your computer and use it in GitHub Desktop.
Save cevr/88e89c06be83a098edb337fbfdc7c1f1 to your computer and use it in GitHub Desktop.
import { action, thunk } from 'easy-peasy';
import mockService from './mock-service';
export default {
todos: {},
// actions
setTodos: action((state, todos) => {
state.todos = todos.reduce((acc, todo) => {
acc[todo.id] = todo;
return acc;
}, {});
}),
// thunks
fetchTodos: thunk(async actions => {
const todos = await mockService.fetchTodos();
actions.setTodos(todos);
}),
add: thunk(async (actions, todo) => {
const updated = await mockService.saveTodo(todo);
actions.setTodos(updated);
}),
toggle: thunk(async (actions, id, { getState }) => {
const todo = getState().todos[id];
if (!todo) return;
const updated = await mockService.updateTodo(id, {
done: !todo.done,
});
actions.setTodos(updated);
}),
delete: thunk(async (actions, id, { getState }) => {
const todo = getState().todos[id];
if (!todo) return;
const updated = await mockService.deleteTodo(id);
actions.setTodos(updated);
}),
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment