Created
December 27, 2018 05:28
-
-
Save kselax/877693b8cbbf238a463bc804be5fa084 to your computer and use it in GitHub Desktop.
reducer of todo app
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 { ADD_TODO, | |
TOGGLE_TODO, | |
SET_ALL_TODOS, | |
ADD_TODO_R, | |
DEL_TODO } from '../actionTypes.js' | |
const initialState = { | |
allIds: [], | |
byIds: {}, | |
total: 0, | |
page: 1 | |
} | |
export default function(state = initialState, action) { | |
try { | |
switch (action.type) { | |
case ADD_TODO: { | |
const { id, content } = action.payload | |
return { | |
...state, | |
allIds: [ ...state.allIds, id ], | |
byIds: { | |
...state.byIds, | |
[id]: { | |
completed: false, | |
content | |
} | |
} | |
} | |
} | |
case ADD_TODO_R: { | |
const { id, content, completed } = action.payload | |
return { | |
...state, | |
allIds: [ ...state.allIds, id ], | |
byIds: { | |
...state.byIds, | |
[id]: { | |
completed, | |
content | |
} | |
} | |
} | |
} | |
case TOGGLE_TODO: { | |
const { id } = action.payload | |
return { | |
...state, | |
byIds: { | |
...state.byIds, | |
[id]: { | |
...state.byIds[id], | |
completed: !state.byIds[id].completed | |
} | |
} | |
} | |
} | |
case DEL_TODO: { | |
const { id } = action.payload | |
const allIds = [ ...state.allIds ] | |
allIds.splice(allIds.indexOf(id), 1) | |
let byIds = Object.assign({}, state.byIds) | |
delete byIds[id] | |
return { | |
...state, | |
allIds: allIds, | |
byIds: byIds | |
} | |
} | |
case SET_ALL_TODOS: { | |
const obj = JSON.parse(action.payload.todos) | |
const todos = obj.items | |
const total = obj.total | |
const page = obj.page | |
console.log(`total = ${total} page = ${page}`); | |
const output = { | |
total: total, | |
allIds: [], | |
byIds: {} | |
} | |
todos.forEach(todo => { | |
output.allIds.push(todo.id) | |
output.byIds = { | |
...output.byIds, | |
[todo.id]: { | |
completed: todo.completed, | |
content: todo.content | |
} | |
} | |
}) | |
return output | |
} | |
default: | |
return state | |
} | |
} catch(e) { | |
// statements | |
console.log(e); | |
return state | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment