View source
const { createStore } = Redux;
const initial = { todos: [] };
function todosReducer(state = initial, action){
switch(action.type){
case 'todo/add':
return { ...state, todos: [...state.todos, { id: Date.now(), text: action.payload, done: false }] };
case 'todo/toggle':
return { ...state, todos: state.todos.map(t => t.id===action.payload ? { ...t, done: !t.done } : t) };
default: return state;
}
}
const store = createStore(todosReducer);
function render(){
const s = store.getState();
document.getElementById('todos-out').textContent = JSON.stringify(s.todos);
}
store.subscribe(render); render();
function addTodo(){ const v = document.getElementById('todo-input').value.trim(); if(!v) return; store.dispatch({type:'todo/add', payload:v}); document.getElementById('todo-input').value=''; }
function toggleFirst(){ const s = store.getState(); const first = s.todos[0]; if(first) store.dispatch({type:'todo/toggle', payload:first.id}); }