42 lines
1.4 KiB
JavaScript
42 lines
1.4 KiB
JavaScript
'use strict'
|
|
const {RECEIVE_TODOS, RECEIVED_TODOS, ADD_TODO, ADDED_TODO} = require('./action_constants')
|
|
const INITIAL_STATE = {toBeAdded: [], items: [], size: 0, lastUpdated: null, fetching: false, error: null}
|
|
|
|
// create an array of todos that are still queued, but not yet added
|
|
const removeToBeAdded = (current, itemToBeRemoved) => {
|
|
if (current.length === 1) return []
|
|
return current.map(item => {
|
|
if (item.text !== itemToBeRemoved.text) return item
|
|
})
|
|
}
|
|
|
|
module.exports = (state = INITIAL_STATE, action) => {
|
|
switch (action.type) {
|
|
// received all todos
|
|
case RECEIVED_TODOS:
|
|
return Object.assign({}, state, {
|
|
items: action.items,
|
|
size: action.items.length,
|
|
lastUpdated: Date.now(),
|
|
})
|
|
// trying to add a todo (request to amazon not yet made)
|
|
case ADD_TODO:
|
|
return Object.assign({}, state, {
|
|
toBeAdded: state.toBeAdded.push(action.item),
|
|
lastUpdated: Date.now(),
|
|
})
|
|
// todo has been added successfully
|
|
case ADDED_TODO:
|
|
// remove the item from the toBeadded array
|
|
const toBeAdded = removeToBeAdded(state.toBeAdded, action.item)
|
|
state.items.push(action.item)
|
|
return Object.assign({}, state, {
|
|
items: state.items,
|
|
size: state.size + 1,
|
|
toBeAdded: toBeAdded,
|
|
lastUpdated: Date.now(),
|
|
})
|
|
default:
|
|
return state
|
|
}
|
|
} |