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="&quot;https://npmcdn.com/react/dist/react.js&quot;"></script>
<script src="https://npmcdn.com/react-dom/dist/react-dom.js"></script>
<div id="root"></div>

Babel + JSX

/* Create a store from a reducer using `createStore`.
 * 
 * Dispatch an action from inside an click event listener using. (You can just attach the listener to `document`.)
 * 
 * Subscribe to state changes and render the current count by setting the `innerHTML` of the body.
 *
 * Bonus: reimplement `createStore`
 */

const counter = (state = 0, action) => {
  switch (action.type) {
    case 'INCREMENT':
      return state + 1;
    case 'DECREMENT':
      return state - 1;
    default:
      return state;
  }
};


const createStore = (reducer) => {
  let state
	let listeners = []
	
	const dispatch = (action) => {
	  state = reducer(state, action);
		listeners.forEach(l => l())
	};
	
	const getState = () => state;
	
	const subscribe = (listener) => {
	  listeners.push(listener);
		return function unsubscribe() {
		  listeners = listeners.filter(
			  l => l !== listener
			);
		}
	};
	
	dispatch({});
	
	return {
	  getState,
		dispatch,
		subscribe
	};
}

const store = createStore(counter);

document.addEventListener('click', () => {
  store.dispatch({ type: 'INCREMENT' });
});

const render = () => {
  document.body.innerHTML = store.getState().toString();
};

render();

store.subscribe(render);

const root = document.getElementById('root');