Slide 1

Slide 1 text

Jeremy Fairbank @elpapapollo / jfairbank Get Started with Redux

Slide 2

Slide 2 text

Software is broken. We are here to fix it. Say [email protected]

Slide 3

Slide 3 text

The Wild West of State

Slide 4

Slide 4 text

...
var $el = $('[data-id="42"]'); var currentName = $el.data('name'); $el.data('name', currentName.toUpperCase()); Data in the DOM

Slide 5

Slide 5 text

Controller View Model Model Model Model Model View View View View MVC

Slide 6

Slide 6 text

View Model Model Model Model Model View Model View Model View Model View Model Model Two-way Data Binding

Slide 7

Slide 7 text

The Wild West of State State is everywhere and anyone can change it!

Slide 8

Slide 8 text

Predictable State Container

Slide 9

Slide 9 text

All application state in one place State Container

Slide 10

Slide 10 text

Predictable Old State REDUCER New State

Slide 11

Slide 11 text

Predictable Old State REDUCER New State • State changes in one place

Slide 12

Slide 12 text

Predictable Old State REDUCER New State • State changes in one place • State changes in well-defined ways

Slide 13

Slide 13 text

Predictable Old State REDUCER New State • State changes in one place • State changes in well-defined ways • Changes are serialized

Slide 14

Slide 14 text

Reducer View State Actions

Slide 15

Slide 15 text

Reducer View State Actions

Slide 16

Slide 16 text

Reducer View React, Angular, Vanilla JS, etc. State Actions

Slide 17

Slide 17 text

Reducer View State Actions Dispatch

Slide 18

Slide 18 text

Reducer View State Actions

Slide 19

Slide 19 text

-
0
+

Slide 20

Slide 20 text

incrementBtn.addEventListener('click', () => { counter.innerText = Number(counter.innerText) + 1; }); decrementBtn.addEventListener('click', () => { counter.innerText = Number(counter.innerText) - 1; });

Slide 21

Slide 21 text

let state = 0; function render() { counter.innerText = state; } incrementBtn.addEventListener('click', () => { state += 1; render(); }); decrementBtn.addEventListener('click', () => { state -= 1; render(); });

Slide 22

Slide 22 text

let state = 0; function render() { counter.innerText = state; } incrementBtn.addEventListener('click', () => { state += 1; render(); }); decrementBtn.addEventListener('click', () => { state -= 1; render(); });

Slide 23

Slide 23 text

let state = 0; function render() { counter.innerText = state; } incrementBtn.addEventListener('click', () => { state += 1; render(); }); decrementBtn.addEventListener('click', () => { state -= 1; render(); });

Slide 24

Slide 24 text

let state = 0; function render() { counter.innerText = state; } incrementBtn.addEventListener('click', () => { state += 1; render(); }); decrementBtn.addEventListener('click', () => { state -= 1; render(); });

Slide 25

Slide 25 text

state += 1; state -= 1; Anyone can access and mutate state

Slide 26

Slide 26 text

state += 1 state -= 1 { type: 'INCREMENT' } { type: 'DECREMENT' } Tokens/descriptors that describe a type of change. Actions

Slide 27

Slide 27 text

function reducer(state = 0, action) { switch (action.type) { case 'INCREMENT': return state + 1; case 'DECREMENT': return state - 1; default: return state; } } Returns new state from current state and action. Reducer

Slide 28

Slide 28 text

function reducer(state = 0, action) { switch (action.type) { case 'INCREMENT': return state + 1; case 'DECREMENT': return state - 1; default: return state; } } Returns new state from current state and action. Reducer

Slide 29

Slide 29 text

function reducer(state = 0, action) { switch (action.type) { case 'INCREMENT': return state + 1; case 'DECREMENT': return state - 1; default: return state; } } Returns new state from current state and action. Reducer

Slide 30

Slide 30 text

function reducer(state = 0, action) { switch (action.type) { case 'INCREMENT': return state + 1; case 'DECREMENT': return state - 1; default: return state; } } Returns new state from current state and action. Reducer

Slide 31

Slide 31 text

function reducer(state = 0, action) { switch (action.type) { case 'INCREMENT': return state + 1; case 'DECREMENT': return state - 1; default: return state; } } Returns new state from current state and action. Reducer

Slide 32

Slide 32 text

function reducer(state = 0, action) { switch (action.type) { case 'INCREMENT': return state + 1; case 'DECREMENT': return state - 1; default: return state; } } Returns new state from current state and action. Reducer

Slide 33

Slide 33 text

function reducer(state = 0, action) { switch (action.type) { case 'INCREMENT': return state + 1; case 'DECREMENT': return state - 1; default: return state; } } Returns new state from current state and action. Reducer

Slide 34

Slide 34 text

Updating state is just a function call now let state = 0; state = reducer(state, { type: 'INCREMENT' }); // 1 state = reducer(state, { type: 'INCREMENT' }); // 2 state = reducer(state, { type: 'DECREMENT' }); // 1 state = reducer(state, { type: 'ADD_2' }); // 1 console.log(state); // 1

Slide 35

Slide 35 text

Updating state is just a function call now let state = 0; state = reducer(state, { type: 'INCREMENT' }); // 1 state = reducer(state, { type: 'INCREMENT' }); // 2 state = reducer(state, { type: 'DECREMENT' }); // 1 state = reducer(state, { type: 'ADD_2' }); // 1 console.log(state); // 1 Unhandled types are ignored

Slide 36

Slide 36 text

function dispatch(action) { state = reducer(state, action); render(); } incrementBtn.addEventListener('click', () => { dispatch({ type: 'INCREMENT' }); }); decrementBtn.addEventListener('click', () => { dispatch({ type: 'DECREMENT' }); }); Decouple event from state change.

Slide 37

Slide 37 text

function dispatch(action) { state = reducer(state, action); render(); } incrementBtn.addEventListener('click', () => { dispatch({ type: 'INCREMENT' }); }); decrementBtn.addEventListener('click', () => { dispatch({ type: 'DECREMENT' }); }); Decouple event from state change.

Slide 38

Slide 38 text

function dispatch(action) { state = reducer(state, action); render(); } incrementBtn.addEventListener('click', () => { dispatch({ type: 'INCREMENT' }); }); decrementBtn.addEventListener('click', () => { dispatch({ type: 'DECREMENT' }); }); Decouple event from state change.

Slide 39

Slide 39 text

function dispatch(action) { state = reducer(state, action); render(); } incrementBtn.addEventListener('click', () => { dispatch({ type: 'INCREMENT' }); }); decrementBtn.addEventListener('click', () => { dispatch({ type: 'DECREMENT' }); }); Decouple event from state change.

Slide 40

Slide 40 text

function dispatch(action) { state = reducer(state, action); render(); } incrementBtn.addEventListener('click', () => { dispatch({ type: 'INCREMENT' }); }); decrementBtn.addEventListener('click', () => { dispatch({ type: 'DECREMENT' }); }); Decouple event from state change.

Slide 41

Slide 41 text

STORE

Slide 42

Slide 42 text

import { createStore } from 'redux'; const store = createStore(reducer, 0); store.getState(); // 0

Slide 43

Slide 43 text

import { createStore } from 'redux'; const store = createStore(reducer, 0); store.getState(); // 0

Slide 44

Slide 44 text

import { createStore } from 'redux'; const store = createStore(reducer, 0); store.getState(); // 0

Slide 45

Slide 45 text

import { createStore } from 'redux'; const store = createStore(reducer, 0); store.getState(); // 0

Slide 46

Slide 46 text

import { createStore } from 'redux'; const store = createStore(reducer, 0); store.getState(); // 0

Slide 47

Slide 47 text

incrementBtn.addEventListener('click', () => { store.dispatch({ type: 'INCREMENT' }); }); decrementBtn.addEventListener('click', () => { store.dispatch({ type: 'DECREMENT' }); }); store.subscribe(() => { counter.innerText = store.getState(); });

Slide 48

Slide 48 text

incrementBtn.addEventListener('click', () => { store.dispatch({ type: 'INCREMENT' }); }); decrementBtn.addEventListener('click', () => { store.dispatch({ type: 'DECREMENT' }); }); store.subscribe(() => { counter.innerText = store.getState(); });

Slide 49

Slide 49 text

incrementBtn.addEventListener('click', () => { store.dispatch({ type: 'INCREMENT' }); }); decrementBtn.addEventListener('click', () => { store.dispatch({ type: 'DECREMENT' }); }); store.subscribe(() => { counter.innerText = store.getState(); });

Slide 50

Slide 50 text

Store Reducer State View 0

Slide 51

Slide 51 text

Store Reducer State View 0

Slide 52

Slide 52 text

Store Reducer State View 0 getState

Slide 53

Slide 53 text

Store Reducer View State 0

Slide 54

Slide 54 text

Store Reducer View State 0 INCREMENT dispatch

Slide 55

Slide 55 text

Store Reducer View State 0 INCREMENT dispatch

Slide 56

Slide 56 text

Store Reducer View State 0

Slide 57

Slide 57 text

Store Reducer View State 1

Slide 58

Slide 58 text

Store Reducer View State 1

Slide 59

Slide 59 text

Store Reducer View State 1 1 subscribe getState

Slide 60

Slide 60 text

incrementBtn.addEventListener('click', () => { store.dispatch({ type: 'INCREMENT' }); }); decrementBtn.addEventListener('click', () => { store.dispatch({ type: 'DECREMENT' }); }); Problems: • Creating actions are cumbersome • Requires direct access to store

Slide 61

Slide 61 text

const increment = () => ({ type: 'INCREMENT', }); const decrement = () => ({ type: 'DECREMENT', }); Reusable functions that create actions Action Creators

Slide 62

Slide 62 text

const increment = () => ({ type: 'INCREMENT', }); const decrement = () => ({ type: 'DECREMENT', }); Reusable functions that create actions Action Creators

Slide 63

Slide 63 text

const increment = () => ({ type: 'INCREMENT', }); const decrement = () => ({ type: 'DECREMENT', }); Reusable functions that create actions Action Creators

Slide 64

Slide 64 text

incrementBtn.addEventListener('click', () => { store.dispatch(increment()); }); decrementBtn.addEventListener('click', () => { store.dispatch(decrement()); }); Problems: • Creating actions are cumbersome • Requires direct access to store

Slide 65

Slide 65 text

const actions = { increment: () => store.dispatch(increment()), decrement: () => store.dispatch(decrement()), }; Automatically dispatch when invoked Bound Action Creators

Slide 66

Slide 66 text

const actions = { increment: () => store.dispatch(increment()), decrement: () => store.dispatch(decrement()), }; Automatically dispatch when invoked Bound Action Creators Manually created

Slide 67

Slide 67 text

const actions = { increment: () => store.dispatch(increment()), decrement: () => store.dispatch(decrement()), }; Automatically dispatch when invoked Bound Action Creators

Slide 68

Slide 68 text

import { bindActionCreators } from 'redux'; const actions = bindActionCreators( { increment, decrement }, store.dispatch ); Automatically dispatch when invoked Bound Action Creators

Slide 69

Slide 69 text

import { bindActionCreators } from 'redux'; const actions = bindActionCreators( { increment, decrement }, store.dispatch ); Automatically dispatch when invoked Bound Action Creators

Slide 70

Slide 70 text

import { bindActionCreators } from 'redux'; const actions = bindActionCreators( { increment, decrement }, store.dispatch ); Automatically dispatch when invoked Bound Action Creators Automatically created

Slide 71

Slide 71 text

Problems: • Creating actions are cumbersome • Requires direct access to store incrementBtn.addEventListener('click', actions.increment); decrementBtn.addEventListener('click', actions.decrement);

Slide 72

Slide 72 text

React +

Slide 73

Slide 73 text

github.com/reactjs/react-redux npm install --save react-redux Official React bindings for Redux React Redux Library

Slide 74

Slide 74 text

Reducer State Actions React Redux

Slide 75

Slide 75 text

React Redux React Application

Slide 76

Slide 76 text

React Redux React Application Provider

Slide 77

Slide 77 text

Component React Redux React Application Provider connect State Action Creators

Slide 78

Slide 78 text

Component Child React Redux React Application Provider connect State Child Action Creators

Slide 79

Slide 79 text

const MyApp = () => (
-
0
+
);

Slide 80

Slide 80 text

import React from 'react'; import { render } from 'react-dom'; import { Provider } from 'react-redux'; render(( ), document.getElementById('main'));

Slide 81

Slide 81 text

import React from 'react'; import { render } from 'react-dom'; import { Provider } from 'react-redux'; render(( ), document.getElementById('main'));

Slide 82

Slide 82 text

import React from 'react'; import { render } from 'react-dom'; import { Provider } from 'react-redux'; render(( ), document.getElementById('main'));

Slide 83

Slide 83 text

import { connect } from 'react-redux'; const mapStateToProps = counter => ({ counter }); function mapDispatchToProps(dispatch) { return bindActionCreators({ onIncrement: increment, onDecrement: decrement, }, dispatch); } const MyAppContainer = connect( mapStateToProps, mapDispatchToProps )(MyApp);

Slide 84

Slide 84 text

import { connect } from 'react-redux'; const mapStateToProps = counter => ({ counter }); function mapDispatchToProps(dispatch) { return bindActionCreators({ onIncrement: increment, onDecrement: decrement, }, dispatch); } const MyAppContainer = connect( mapStateToProps, mapDispatchToProps )(MyApp);

Slide 85

Slide 85 text

import { connect } from 'react-redux'; const mapStateToProps = counter => ({ counter }); function mapDispatchToProps(dispatch) { return bindActionCreators({ onIncrement: increment, onDecrement: decrement, }, dispatch); } const MyAppContainer = connect( mapStateToProps, mapDispatchToProps )(MyApp);

Slide 86

Slide 86 text

import { connect } from 'react-redux'; const mapStateToProps = counter => ({ counter }); function mapDispatchToProps(dispatch) { return bindActionCreators({ onIncrement: increment, onDecrement: decrement, }, dispatch); } const MyAppContainer = connect( mapStateToProps, mapDispatchToProps )(MyApp);

Slide 87

Slide 87 text

import { connect } from 'react-redux'; const mapStateToProps = counter => ({ counter }); function mapDispatchToProps(dispatch) { return bindActionCreators({ onIncrement: increment, onDecrement: decrement, }, dispatch); } const MyAppContainer = connect( mapStateToProps, mapDispatchToProps )(MyApp);

Slide 88

Slide 88 text

const MyApp = (props) => (
-
{props.counter}
+
);

Slide 89

Slide 89 text

const MyApp = (props) => (
-
{props.counter}
+
); Store state mapStateToProps

Slide 90

Slide 90 text

const MyApp = (props) => (
-
{props.counter}
+
); Bound action creators mapDispatchToProps

Slide 91

Slide 91 text

Immutable Object State

Slide 92

Slide 92 text

const initialState = { counter: 0, car: { color: 'red', }, };

Slide 93

Slide 93 text

const initialState = { counter: 0, car: { color: 'red', }, };

Slide 94

Slide 94 text

const initialState = { counter: 0, car: { color: 'red', }, };

Slide 95

Slide 95 text

const increment = () => ({ type: 'INCREMENT', }); const decrement = () => ({ type: 'DECREMENT', }); const changeColor = color => ({ type: 'CHANGE_COLOR', payload: color, });

Slide 96

Slide 96 text

const increment = () => ({ type: 'INCREMENT', }); const decrement = () => ({ type: 'DECREMENT', }); const changeColor = color => ({ type: 'CHANGE_COLOR', payload: color, });

Slide 97

Slide 97 text

const increment = () => ({ type: 'INCREMENT', }); const decrement = () => ({ type: 'DECREMENT', }); const changeColor = color => ({ type: 'CHANGE_COLOR', payload: color, });

Slide 98

Slide 98 text

function reducer(state = initialState, action) { switch (action.type) { case 'INCREMENT': return { ...state, counter: state.counter + 1 }; case 'DECREMENT': return { ...state, counter: state.counter - 1 }; case 'CHANGE_COLOR': return { ...state, car: { color: action.payload } }; default: return state; } }

Slide 99

Slide 99 text

function reducer(state = initialState, action) { switch (action.type) { case 'INCREMENT': return { ...state, counter: state.counter + 1 }; case 'DECREMENT': return { ...state, counter: state.counter - 1 }; case 'CHANGE_COLOR': return { ...state, car: { color: action.payload } }; default: return state; } }

Slide 100

Slide 100 text

function reducer(state = initialState, action) { switch (action.type) { case 'INCREMENT': return { ...state, counter: state.counter + 1 }; case 'DECREMENT': return { ...state, counter: state.counter - 1 }; case 'CHANGE_COLOR': return { ...state, car: { color: action.payload } }; default: return state; } }

Slide 101

Slide 101 text

function reducer(state = initialState, action) { switch (action.type) { case 'INCREMENT': return { ...state, counter: state.counter + 1 }; case 'DECREMENT': return { ...state, counter: state.counter - 1 }; case 'CHANGE_COLOR': return { ...state, car: { color: action.payload } }; default: return state; } }

Slide 102

Slide 102 text

function reducer(state = initialState, action) { switch (action.type) { case 'INCREMENT': return { ...state, counter: state.counter + 1 }; case 'DECREMENT': return { ...state, counter: state.counter - 1 }; case 'CHANGE_COLOR': return { ...state, car: { color: action.payload } }; default: return state; } }

Slide 103

Slide 103 text

function reducer(state = initialState, action) { switch (action.type) { case 'INCREMENT': return { ...state, counter: state.counter + 1 }; case 'DECREMENT': return { ...state, counter: state.counter - 1 }; case 'CHANGE_COLOR': return { ...state, car: { color: action.payload } }; default: return state; } }

Slide 104

Slide 104 text

store.subscribe(() => { console.log('state =', store.getState()); }); store.dispatch(increment()); store.dispatch(changeColor('green')); // state = { counter: 1, car: { color: 'red' } } // state = { counter: 1, car: { color: 'green' } }

Slide 105

Slide 105 text

store.subscribe(() => { console.log('state =', store.getState()); }); store.dispatch(increment()); store.dispatch(changeColor('green')); // state = { counter: 1, car: { color: 'red' } } // state = { counter: 1, car: { color: 'green' } }

Slide 106

Slide 106 text

store.subscribe(() => { console.log('state =', store.getState()); }); store.dispatch(increment()); store.dispatch(changeColor('green')); // state = { counter: 1, car: { color: 'red' } } // state = { counter: 1, car: { color: 'green' } }

Slide 107

Slide 107 text

function reducer(state = initialState, action) { }

Slide 108

Slide 108 text

Reducer Composition Create modular reducers for better organization and readability

Slide 109

Slide 109 text

Root Reducer Counter Reducer Car Reducer

Slide 110

Slide 110 text

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

Slide 111

Slide 111 text

const initialState = { color: 'red' }; function carReducer(state = initialState, action) { switch (action.type) { case 'CHANGE_COLOR': return { ...state, color: action.payload }; default: return state; } }

Slide 112

Slide 112 text

const initialState = { color: 'red' }; function carReducer(state = initialState, action) { switch (action.type) { case 'CHANGE_COLOR': return { ...state, color: action.payload }; default: return state; } }

Slide 113

Slide 113 text

const initialState = { color: 'red' }; function carReducer(state = initialState, action) { switch (action.type) { case 'CHANGE_COLOR': return { ...state, color: action.payload }; default: return state; } }

Slide 114

Slide 114 text

function reducer(state = {}, action) { return { counter: counterReducer(state.counter, action), car: carReducer(state.car, action), }; }

Slide 115

Slide 115 text

function reducer(state = {}, action) { return { counter: counterReducer(state.counter, action), car: carReducer(state.car, action), }; }

Slide 116

Slide 116 text

function reducer(state = {}, action) { return { counter: counterReducer(state.counter, action), car: carReducer(state.car, action), }; }

Slide 117

Slide 117 text

function reducer(state = {}, action) { return { counter: counterReducer(state.counter, action), car: carReducer(state.car, action), }; }

Slide 118

Slide 118 text

import { combineReducers } from 'redux'; const reducer = combineReducers({ counter: counterReducer, car: carReducer, });

Slide 119

Slide 119 text

import { combineReducers } from 'redux'; const reducer = combineReducers({ counter: counterReducer, car: carReducer, });

Slide 120

Slide 120 text

import { combineReducers } from 'redux'; const reducer = combineReducers({ counter: counterReducer, car: carReducer, });

Slide 121

Slide 121 text

Root Reducer Counter Reducer Car Reducer Engine Reducer Tire Reducer … … …

Slide 122

Slide 122 text

Root Reducer Counter Reducer Car Reducer Engine Reducer Tire Reducer … … …

Slide 123

Slide 123 text

Root Reducer Counter Reducer Car Reducer Engine Reducer Tire Reducer … … …

Slide 124

Slide 124 text

Interact with APIs?

Slide 125

Slide 125 text

Middleware Enhance Redux applications

Slide 126

Slide 126 text

• Logging Middleware Enhance Redux applications

Slide 127

Slide 127 text

• Logging • Debugging Middleware Enhance Redux applications

Slide 128

Slide 128 text

• Logging • Debugging • API interaction Middleware Enhance Redux applications

Slide 129

Slide 129 text

• Logging • Debugging • API interaction • Custom actions Middleware Enhance Redux applications

Slide 130

Slide 130 text

Reducer View State Actions Middleware

Slide 131

Slide 131 text

Reducer View State Actions Middleware Intercept

Slide 132

Slide 132 text

const logMiddleware = api => next => action => { console.log('dispatch', action); const result = next(action); console.log('state =', api.getState()); return result; };

Slide 133

Slide 133 text

const logMiddleware = api => next => action => { console.log('dispatch', action); const result = next(action); console.log('state =', api.getState()); return result; };

Slide 134

Slide 134 text

const logMiddleware = api => next => action => { console.log('dispatch', action); const result = next(action); console.log('state =', api.getState()); return result; };

Slide 135

Slide 135 text

const logMiddleware = api => next => action => { console.log('dispatch', action); const result = next(action); console.log('state =', api.getState()); return result; };

Slide 136

Slide 136 text

const logMiddleware = api => next => action => { console.log('dispatch', action); const result = next(action); console.log('state =', api.getState()); return result; };

Slide 137

Slide 137 text

const logMiddleware = api => next => action => { console.log('dispatch', action); const result = next(action); console.log('state =', api.getState()); return result; };

Slide 138

Slide 138 text

const logMiddleware = api => next => action => { console.log('dispatch', action); const result = next(action); console.log('state =', api.getState()); return result; };

Slide 139

Slide 139 text

const logMiddleware = api => next => action => { console.log('dispatch', action); const result = next(action); console.log('state =', api.getState()); return result; };

Slide 140

Slide 140 text

const logMiddleware = api => next => action => { console.log('dispatch', action); const result = next(action); console.log('state =', api.getState()); return result; };

Slide 141

Slide 141 text

import { applyMiddleware } from 'redux'; const store = createStore( reducer, applyMiddleware(logMiddleware) ); store.dispatch(increment()); store.dispatch(changeColor('green')); // dispatch { type: 'INCREMENT' } // state = { counter: 1, car: { color: 'red' } } // dispatch { type: 'CHANGE_COLOR', payload: 'green' } // state = { counter: 1, car: { color: 'green' } }

Slide 142

Slide 142 text

import { applyMiddleware } from 'redux'; const store = createStore( reducer, applyMiddleware(logMiddleware) ); store.dispatch(increment()); store.dispatch(changeColor('green')); // dispatch { type: 'INCREMENT' } // state = { counter: 1, car: { color: 'red' } } // dispatch { type: 'CHANGE_COLOR', payload: 'green' } // state = { counter: 1, car: { color: 'green' } }

Slide 143

Slide 143 text

import { applyMiddleware } from 'redux'; const store = createStore( reducer, applyMiddleware(logMiddleware) ); store.dispatch(increment()); store.dispatch(changeColor('green')); // dispatch { type: 'INCREMENT' } // state = { counter: 1, car: { color: 'red' } } // dispatch { type: 'CHANGE_COLOR', payload: 'green' } // state = { counter: 1, car: { color: 'green' } }

Slide 144

Slide 144 text

import { applyMiddleware } from 'redux'; const store = createStore( reducer, applyMiddleware(logMiddleware) ); store.dispatch(increment()); store.dispatch(changeColor('green')); // dispatch { type: 'INCREMENT' } // state = { counter: 1, car: { color: 'red' } } // dispatch { type: 'CHANGE_COLOR', payload: 'green' } // state = { counter: 1, car: { color: 'green' } }

Slide 145

Slide 145 text

import { applyMiddleware } from 'redux'; const store = createStore( reducer, applyMiddleware(logMiddleware) ); store.dispatch(increment()); store.dispatch(changeColor('green')); // dispatch { type: 'INCREMENT' } // state = { counter: 1, car: { color: 'red' } } // dispatch { type: 'CHANGE_COLOR', payload: 'green' } // state = { counter: 1, car: { color: 'green' } }

Slide 146

Slide 146 text

const initialState = { status: 'READY', user: null, };

Slide 147

Slide 147 text

function reducer(state = initialState, action) { switch (action.type) { case 'REQUEST_USER': return { ...state, status: 'FETCHING' }; case 'RECEIVE_USER': return { ...state, status: 'SUCCESS', user: action.payload, }; default: return state; } }

Slide 148

Slide 148 text

function reducer(state = initialState, action) { switch (action.type) { case 'REQUEST_USER': return { ...state, status: 'FETCHING' }; case 'RECEIVE_USER': return { ...state, status: 'SUCCESS', user: action.payload, }; default: return state; } }

Slide 149

Slide 149 text

function reducer(state = initialState, action) { switch (action.type) { case 'REQUEST_USER': return { ...state, status: 'FETCHING' }; case 'RECEIVE_USER': return { ...state, status: 'SUCCESS', user: action.payload, }; default: return state; } }

Slide 150

Slide 150 text

const requestUser = id => ({ type: 'REQUEST_USER', payload: id, }); const receiveUser = user => ({ type: 'RECEIVE_USER', payload: user, });

Slide 151

Slide 151 text

const store = createStore(reducer); function fetchUser(id) { store.dispatch(requestUser(id)); axios.get(`/users/${id}`) .then(({ data: user }) => { store.dispatch(receiveUser(user)); }); } fetchUser(1);

Slide 152

Slide 152 text

const store = createStore(reducer); function fetchUser(id) { store.dispatch(requestUser(id)); axios.get(`/users/${id}`) .then(({ data: user }) => { store.dispatch(receiveUser(user)); }); } fetchUser(1);

Slide 153

Slide 153 text

const store = createStore(reducer); function fetchUser(id) { store.dispatch(requestUser(id)); axios.get(`/users/${id}`) .then(({ data: user }) => { store.dispatch(receiveUser(user)); }); } fetchUser(1);

Slide 154

Slide 154 text

const thunkMiddleware = api => next => action => { if (typeof action === 'function') { return action(api.dispatch); } return next(action); }; const store = createStore( reducer, applyMiddleware(thunkMiddleware) );

Slide 155

Slide 155 text

const thunkMiddleware = api => next => action => { if (typeof action === 'function') { return action(api.dispatch); } return next(action); }; const store = createStore( reducer, applyMiddleware(thunkMiddleware) );

Slide 156

Slide 156 text

const thunkMiddleware = api => next => action => { if (typeof action === 'function') { return action(api.dispatch); } return next(action); }; const store = createStore( reducer, applyMiddleware(thunkMiddleware) );

Slide 157

Slide 157 text

const thunkMiddleware = api => next => action => { if (typeof action === 'function') { return action(api.dispatch); } return next(action); }; const store = createStore( reducer, applyMiddleware(thunkMiddleware) );

Slide 158

Slide 158 text

function fetchUser(id) { return dispatch => { dispatch(requestUser(id)); return axios.get(`/users/${id}`) .then(({ data: user }) => { dispatch(receiveUser(user)); }); }; } store.dispatch(fetchUser(1));

Slide 159

Slide 159 text

function fetchUser(id) { return dispatch => { dispatch(requestUser(id)); return axios.get(`/users/${id}`) .then(({ data: user }) => { dispatch(receiveUser(user)); }); }; } store.dispatch(fetchUser(1)); Action Creator

Slide 160

Slide 160 text

function fetchUser(id) { return dispatch => { dispatch(requestUser(id)); return axios.get(`/users/${id}`) .then(({ data: user }) => { dispatch(receiveUser(user)); }); }; } store.dispatch(fetchUser(1)); Action

Slide 161

Slide 161 text

function fetchUser(id) { return dispatch => { dispatch(requestUser(id)); return axios.get(`/users/${id}`) .then(({ data: user }) => { dispatch(receiveUser(user)); }); }; } store.dispatch(fetchUser(1));

Slide 162

Slide 162 text

Alternative Async Middleware

Slide 163

Slide 163 text

redux-saga.js.org

Slide 164

Slide 164 text

• Uses ES6 generator functions redux-saga.js.org

Slide 165

Slide 165 text

• Uses ES6 generator functions • Write asynchronous code in synchronous manner redux-saga.js.org

Slide 166

Slide 166 text

• Uses ES6 generator functions • Write asynchronous code in synchronous manner • Great for coordinating multiple API calls redux-saga.js.org

Slide 167

Slide 167 text

• Uses ES6 generator functions • Write asynchronous code in synchronous manner • Great for coordinating multiple API calls • Great for forking background tasks redux-saga.js.org

Slide 168

Slide 168 text

redux-observable.js.org

Slide 169

Slide 169 text

redux-observable.js.org • Uses RxJS observables

Slide 170

Slide 170 text

redux-observable.js.org • Uses RxJS observables • Write asynchronous code with declarative observable chains

Slide 171

Slide 171 text

redux-observable.js.org • Uses RxJS observables • Write asynchronous code with declarative observable chains • Great for composing asynchronous operations

Slide 172

Slide 172 text

redux-observable.js.org • Uses RxJS observables • Write asynchronous code with declarative observable chains • Great for composing asynchronous operations • Very concise code

Slide 173

Slide 173 text

And plenty more options…

Slide 174

Slide 174 text

• redux-logic And plenty more options…

Slide 175

Slide 175 text

• redux-logic • redux-ship And plenty more options…

Slide 176

Slide 176 text

• redux-logic • redux-ship • redux-promise And plenty more options…

Slide 177

Slide 177 text

• redux-logic • redux-ship • redux-promise • redux-api-middleware And plenty more options…

Slide 178

Slide 178 text

× ✓ Testing

Slide 179

Slide 179 text

const state = { counter: 0, car: { color: 'red' }, }; it('returns initial state', () => { expect(reducer(undefined, {})).toEqual(state); }); it('increments the number', () => { const subject = reducer(state, increment()).counter; expect(subject).toBe(1); }); it('changes the car color', () => { const subject = reducer(state, changeColor('green')).car.color; expect(subject).toBe('green'); }); Easy reducer unit tests!

Slide 180

Slide 180 text

it('creates an INCREMENT action', () => { expect(increment()).toEqual({ type: 'INCREMENT' }); }); it('creates a CHANGE_COLOR action', () => { expect(changeColor('blue')).toEqual({ type: 'CHANGE_COLOR', payload: 'blue', }); }); You can test action creators, but not really necessary.

Slide 181

Slide 181 text

However, you should test async action creators. function fetchUser(id) { return dispatch => { dispatch(requestUser(id)); return axios.get(`/users/${id}`) .then(({ data: user }) => { dispatch(receiveUser(user)); }); }; }

Slide 182

Slide 182 text

import td from 'testdouble'; const axios = td.replace('axios'); it('fetches a user', () => { // Arrange const dispatch = td.function(); td.when(axios.get('/users/1')).thenResolve({ data: 'fake user' }); // Act return fetchUser(1)(dispatch).then(() => { const subject = td.matchers.captor(); td.verify(dispatch(subject.capture())); // Assert expect(subject.values[0]).toEqual(requestUser(1)); expect(subject.values[1]).toEqual(receiveUser('fake user’)); }); }); Unit test with test doubles

Slide 183

Slide 183 text

import td from 'testdouble'; const axios = td.replace('axios'); it('fetches a user', () => { // Arrange const dispatch = td.function(); td.when(axios.get('/users/1')).thenResolve({ data: 'fake user' }); // Act return fetchUser(1)(dispatch).then(() => { const subject = td.matchers.captor(); td.verify(dispatch(subject.capture())); // Assert expect(subject.values[0]).toEqual(requestUser(1)); expect(subject.values[1]).toEqual(receiveUser('fake user’)); }); });

Slide 184

Slide 184 text

import td from 'testdouble'; const axios = td.replace('axios'); it('fetches a user', () => { // Arrange const dispatch = td.function(); td.when(axios.get('/users/1')).thenResolve({ data: 'fake user' }); // Act return fetchUser(1)(dispatch).then(() => { const subject = td.matchers.captor(); td.verify(dispatch(subject.capture())); // Assert expect(subject.values[0]).toEqual(requestUser(1)); expect(subject.values[1]).toEqual(receiveUser('fake user’)); }); });

Slide 185

Slide 185 text

import td from 'testdouble'; const axios = td.replace('axios'); it('fetches a user', () => { // Arrange const dispatch = td.function(); td.when(axios.get('/users/1')).thenResolve({ data: 'fake user' }); // Act return fetchUser(1)(dispatch).then(() => { const subject = td.matchers.captor(); td.verify(dispatch(subject.capture())); // Assert expect(subject.values[0]).toEqual(requestUser(1)); expect(subject.values[1]).toEqual(receiveUser('fake user’)); }); });

Slide 186

Slide 186 text

import td from 'testdouble'; const axios = td.replace('axios'); it('fetches a user', () => { // Arrange const dispatch = td.function(); td.when(axios.get('/users/1')).thenResolve({ data: 'fake user' }); // Act return fetchUser(1)(dispatch).then(() => { const subject = td.matchers.captor(); td.verify(dispatch(subject.capture())); // Assert expect(subject.values[0]).toEqual(requestUser(1)); expect(subject.values[1]).toEqual(receiveUser('fake user’)); }); });

Slide 187

Slide 187 text

import td from 'testdouble'; const axios = td.replace('axios'); it('fetches a user', () => { // Arrange const dispatch = td.function(); td.when(axios.get('/users/1')).thenResolve({ data: 'fake user' }); // Act return fetchUser(1)(dispatch).then(() => { const subject = td.matchers.captor(); td.verify(dispatch(subject.capture())); // Assert expect(subject.values[0]).toEqual(requestUser(1)); expect(subject.values[1]).toEqual(receiveUser('fake user’)); }); });

Slide 188

Slide 188 text

import td from 'testdouble'; const axios = td.replace('axios'); it('fetches a user', () => { // Arrange const dispatch = td.function(); td.when(axios.get('/users/1')).thenResolve({ data: 'fake user' }); // Act return fetchUser(1)(dispatch).then(() => { const subject = td.matchers.captor(); td.verify(dispatch(subject.capture())); // Assert expect(subject.values[0]).toEqual(requestUser(1)); expect(subject.values[1]).toEqual(receiveUser('fake user’)); }); });

Slide 189

Slide 189 text

import td from 'testdouble'; const axios = td.replace('axios'); it('fetches a user', () => { // Arrange const dispatch = td.function(); td.when(axios.get('/users/1')).thenResolve({ data: 'fake user' }); // Act return fetchUser(1)(dispatch).then(() => { const subject = td.matchers.captor(); td.verify(dispatch(subject.capture())); // Assert expect(subject.values[0]).toEqual(requestUser(1)); expect(subject.values[1]).toEqual(receiveUser('fake user’)); }); });

Slide 190

Slide 190 text

Use integration tests to ensure all pieces work together. Allow store, reducer, and actions to all interact .

Slide 191

Slide 191 text

it('fetches a user', () => { // Arrange const store = createStore(reducer, applyMiddleware(thunkMiddleware)); td.replace(axios, 'get'); td.when(axios.get('/users/1')).thenResolve({ data: 'fake user' }); // Act const promise = store.dispatch(fetchUser(1)); const subject = store.getState; // Assert expect(subject()).toEqual({ status: 'FETCHING', user: null }); return promise.then(() => { expect(subject()).toEqual({ status: 'SUCCESS', user: 'fake user' }); }); });

Slide 192

Slide 192 text

it('fetches a user', () => { // Arrange const store = createStore(reducer, applyMiddleware(thunkMiddleware)); td.replace(axios, 'get'); td.when(axios.get('/users/1')).thenResolve({ data: 'fake user' }); // Act const promise = store.dispatch(fetchUser(1)); const subject = store.getState; // Assert expect(subject()).toEqual({ status: 'FETCHING', user: null }); return promise.then(() => { expect(subject()).toEqual({ status: 'SUCCESS', user: 'fake user' }); }); });

Slide 193

Slide 193 text

it('fetches a user', () => { // Arrange const store = createStore(reducer, applyMiddleware(thunkMiddleware)); td.replace(axios, 'get'); td.when(axios.get('/users/1')).thenResolve({ data: 'fake user' }); // Act const promise = store.dispatch(fetchUser(1)); const subject = store.getState; // Assert expect(subject()).toEqual({ status: 'FETCHING', user: null }); return promise.then(() => { expect(subject()).toEqual({ status: 'SUCCESS', user: 'fake user' }); }); });

Slide 194

Slide 194 text

it('fetches a user', () => { // Arrange const store = createStore(reducer, applyMiddleware(thunkMiddleware)); td.replace(axios, 'get'); td.when(axios.get('/users/1')).thenResolve({ data: 'fake user' }); // Act const promise = store.dispatch(fetchUser(1)); const subject = store.getState; // Assert expect(subject()).toEqual({ status: 'FETCHING', user: null }); return promise.then(() => { expect(subject()).toEqual({ status: 'SUCCESS', user: 'fake user' }); }); });

Slide 195

Slide 195 text

it('fetches a user', () => { // Arrange const store = createStore(reducer, applyMiddleware(thunkMiddleware)); td.replace(axios, 'get'); td.when(axios.get('/users/1')).thenResolve({ data: 'fake user' }); // Act const promise = store.dispatch(fetchUser(1)); const subject = store.getState; // Assert expect(subject()).toEqual({ status: 'FETCHING', user: null }); return promise.then(() => { expect(subject()).toEqual({ status: 'SUCCESS', user: 'fake user' }); }); });

Slide 196

Slide 196 text

Resources • Redux • redux.js.org • egghead.io/courses/getting-started-with- redux • React • github.com/reactjs/react-redux

Slide 197

Slide 197 text

Thanks! Slides: bit.ly/redux-connect Jeremy Fairbank @elpapapollo / jfairbank