//Here state refers to an individual todo object
const todo = (state, action) => {
switch(action.type) {
case 'ADD_TODO': return {
id: action.id,
text: action.text,
completed: false
}
case 'TOGGLE_TODO':
if (state.id === action.id)
return Object.assign({}, state, { completed: !state.completed });
return state;
default: return state;
}
};
const todos = (state = [], action) => {
switch(action.type) {
case 'ADD_TODO':
return [
...state,
todo(undefined, action)
];
case 'TOGGLE_TODO': {
return state.map(t => todo(t, action));
}
default:
return state;
}
};
const visibilityFilter = (
state = 'SHOW_ALL',
action
) => {
switch(action.type) {
case 'SET_VISIBILITY_FILTER':
return action.filter;
default:
return state;
}
}
const { combineReducers } = Redux;
//The keys are the object of the state that the individual reducer will need to manage; and the values represent the reducer that the combine reducer should call to update the respective attrbiute of the state object as mentioned in the key.
/*
const todoApp = combineReducer({
todos: todos,
visibilityFilter: visibilityFilter
});
*/
//Using ES6 object literal shorthand we can eliminate the key:value pair to only list of keys when key and value are same in an object
const todoApp = combineReducers({
todos, visibilityFilter
});
const { createStore } = Redux;
const store = createStore(todoApp);
console.log('Initial state: ');
console.log(store.getState());
console.log('------------------');
console.log('Dispatching ADD_TODO');
store.dispatch({
type: 'ADD_TODO',
id: 0,
text: 'Learn React'
});
console.log('Current State: ')
console.log(store.getState());
console.log('------------------');
console.log('Dispatching TOGGLE_TODO');
store.dispatch({
type: 'TOGGLE_TODO',
id: 0
});
console.log('Current State: ')
console.log(store.getState());
console.log('------------------');
console.log('Dispatching...
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.