Created
May 30, 2017 18:44
-
-
Save Astrovic/4acc05e333a0b34f151b7595d4ed90a0 to your computer and use it in GitHub Desktop.
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
const { createStore, combineReducers } = Redux; | |
// ACTIONS CONST | |
const ADD_TODO = 'ADD_TODO'; | |
const TOGGLE_TODO = 'TOGGLE_TODO'; | |
const DELETE_TODO = 'DELETE_TODO'; | |
const SET_VISIBILITY_FILTER = 'SET_VISIBILITY_FILTER'; | |
// ACTIONS CREATOR | |
// TODOLIST AC | |
let nextTodoId = 0; | |
const addTodo = text => { | |
const action = { | |
type: ADD_TODO, | |
title: text, | |
id: nextTodoId++ | |
}; | |
return action; | |
}; | |
const toggleTodo = id => { | |
const action = { | |
type: TOGGLE_TODO, | |
id: id | |
} | |
return action; | |
}; | |
const deleteTodo = id => { | |
const action = { | |
type: DELETE_TODO, | |
id: id | |
} | |
return action; | |
}; | |
// FILTER AC | |
const setVisibilityFilter = filter => { | |
return { | |
type: SET_VISIBILITY_FILTER, | |
filter: filter | |
} | |
} | |
// REDUCERS | |
const initialState = []; | |
function todolistReducer(state = [] /*initialState*/, action) { | |
switch(action.type) { | |
case 'ADD_TODO': | |
// create a copy of the state, and add the new todo | |
return state.concat({ | |
title: action.title, | |
id: action.id, | |
done: false | |
}) | |
case 'TOGGLE_TODO': | |
return state.map(todo => { | |
if (todo.id == action.id) { | |
//return {...todo,done: !todo.done} // ES2015 | |
return Object.assign({}, todo, { | |
done: !todo.done | |
}) | |
} | |
return todo | |
} | |
); | |
case 'DELETE_TODO': | |
return state.filter(todo => todo.id!=action.id) | |
default: | |
return state; | |
} | |
}; | |
function visibilityFilterReducer(state = 'ALL', action){ | |
console.log(action.type) | |
switch(action.type){ | |
case 'SET_VISIBILITY_FILTER': | |
return action.filter; | |
default: | |
return state; | |
} | |
} | |
const reducer = combineReducers({ | |
todolist : todolistReducer, | |
visibilityFilter : visibilityFilterReducer | |
}) | |
// STORE | |
const store = Redux.createStore(reducer)//(todolistReducer); | |
// TEST | |
store.dispatch(addTodo("Preparare la lezione")); | |
store.dispatch(addTodo("Comprare regali")); | |
store.dispatch(addTodo("Andare in vacanza")); | |
store.getState(); | |
store.dispatch(toggleTodo(2)); | |
store.dispatch(setVisibilityFilter("ACTIVE")); | |
store.getState(); | |
store.dispatch(deleteTodo(1)); | |
store.getState(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment