// https://egghead.io/lessons/javascript-redux-writing-a-counter-reducer-with-tests
// Reducer function accepts state and action as arguments and returns the new state
const counter = (state = 0, action) => {
switch (action.type) {
case 'INCREMENT':
return state + 1;
case 'DECREMENT':
return state - 1;
default:
return state;
}
}
const { createStore } = Redux;
// Equivalent:
// ES5: var createStore = Redux.createStore;
// Node: import { createStore } from 'redux';
console.log(createStore);
// When we create the store we need to specify the Reducer function
const store = createStore(counter);
// The store has 3 important methods:
// 1. Get state
console.log(store.getState());
// 2. Dispatch
store.dispatch({ type : 'INCREMENT' });
console.log(store.getState());
const render = () => {
document.body.innerHTML = '<h1>' + store.getState() + '</h1>';
}
// 3. Subscribe: Let's you register a call back that will be called any time an action has been dispatched
store.subscribe(render);
render();
document.addEventListener('click', () => {
store.dispatch({type:'INCREMENT'});
});
/*
// If we pass in an INCREMENT action it should return 1
expect(
counter(0, {
type: 'INCREMENT'
})
).toEqual(1);
// If we pass in an INCREMENT action but with state being 1 it should return 2
expect(
counter(1, {
type: 'INCREMENT'
})
).toEqual(2);
expect(
counter(2, {
type: 'DECREMENT'
})
).toEqual(1);
expect(
counter(1, {
type: 'DECREMENT'
})
).toEqual(0);
// What if we pass an unknown action?
expect(
counter(134, {
type: 'SOMETHING_ELSE'
})
).toEqual(134);
expect(
counter(undefined, {})
).toEqual(0);
console.log('Tests passed');
*/
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.