Workshop Base Fiddle
by Ayité D'almeida
HTML
<script src="https://npmcdn.com/redux/dist/redux.js"></script>
<script src="https://npmcdn.com/react-redux/dist/react-redux.js"></script>
<script src="https://npmcdn.com/expect/umd/expect.js"></script>
<script src="https://wzrd.in/standalone/deep-freeze@latest"></script>
<script src="https://npmcdn.com/react-dom/dist/react-dom.js"></script>
<script src="https://npmcdn.com/react/dist/react.js"></script>
<div id="root"></div>
Babel + JSX
(function() {
'use strict';
/* Write a todo list reducer
* ADD_ACTION adds a todo with `id`, `text`, and `completed`
* TOGGLE_TODO toggles a todo's `completed` field
* Don't mutate the state!
* Use tests to verify.
*/
const todo = (state, action) => {
switch(action.type) {
case 'ADD_TODO' :
return
{
id: action.id,
text: action.text,
completed: false
}
}
};
const todos = (state = [], action) => {
switch(action.type) {
case 'ADD_TODO' :
return [
...state, //previous state +
{ // new state
id: action.id,
text:action.text,
completed:false
}
];
case 'TOGGLE_TODO' :
return state.map(todo => {
if(todo.id !== action.id) {
return todo;
}
return {
...todo,
completed: !todo.completed
}});
default:
return state;
}
};
/* Tests */
const testAddTodo = () => {
const stateBefore = [];
const action = {
type: 'ADD_TODO',
id: 0,
text: 'Learn Redux'
};
const stateAfter = [
{
id: 0,
text: 'Learn Redux',
completed: false
}
];
deepFreeze(stateBefore);
deepFreeze(action);
expect(
todos(stateBefore, action)
).toEqual(stateAfter);
};
const testToggleTodo = () => {
const stateBefore = [
{
id: 0,
text: 'Learn Redux',
completed: false
},
{
id: 1,
text: 'Go shopping',
completed: false
}
];
const action = {
type: 'TOGGLE_TODO',
id: 1
};
const stateAfter = [
{
id: 0,
text: 'Learn Redux',
completed: false
},
{
id: 1,
text: 'Go shopping',
completed: true
}
];
deepFreeze(stateBefore);
deepFreeze(action);
...