$30 off During Our Annual Pro Sale. View Details »

Scenic City Summit 2017: Get Started with Redux

Scenic City Summit 2017: Get Started with Redux

Jeremy Fairbank

July 28, 2017
Tweet

More Decks by Jeremy Fairbank

Other Decks in Programming

Transcript

  1. Jeremy Fairbank
    @elpapapollo / jfairbank
    Get Started with
    Redux

    View Slide

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

    View Slide

  3. The Wild West of State

    View Slide


  4. ...

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

    View Slide

  5. Controller
    View
    Model
    Model
    Model
    Model
    Model
    View
    View
    View
    View
    MVC

    View Slide

  6. View
    Model
    Model
    Model
    Model
    Model
    View
    Model
    View
    Model
    View
    Model
    View
    Model
    Model
    Two-way Data Binding

    View Slide

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

    View Slide

  8. Predictable
    State Container

    View Slide

  9. All application
    state in one place
    State Container

    View Slide

  10. Predictable
    Old
    State
    REDUCER
    New
    State

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

  14. Reducer
    View
    State
    Actions

    View Slide

  15. Reducer
    View
    State
    Actions

    View Slide

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

    View Slide

  17. Reducer
    View
    State
    Actions
    Dispatch

    View Slide

  18. Reducer
    View
    State
    Actions

    View Slide

  19. -
    0
    +

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

  27. 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

    View Slide

  28. 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

    View Slide

  29. 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

    View Slide

  30. 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

    View Slide

  31. 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

    View Slide

  32. 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

    View Slide

  33. 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

    View Slide

  34. 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

    View Slide

  35. 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

    View Slide

  36. 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.

    View Slide

  37. 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.

    View Slide

  38. 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.

    View Slide

  39. 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.

    View Slide

  40. 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.

    View Slide

  41. STORE

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

  50. Store
    Reducer
    State
    View
    0

    View Slide

  51. Store
    Reducer
    State
    View
    0

    View Slide

  52. Store
    Reducer
    State
    View
    0
    getState

    View Slide

  53. Store
    Reducer
    View
    State
    0

    View Slide

  54. Store
    Reducer
    View
    State
    0
    INCREMENT
    dispatch

    View Slide

  55. Store
    Reducer
    View
    State
    0
    INCREMENT
    dispatch

    View Slide

  56. Store
    Reducer
    View
    State
    0

    View Slide

  57. Store
    Reducer
    View
    State
    1

    View Slide

  58. Store
    Reducer
    View
    State
    1

    View Slide

  59. Store
    Reducer
    View
    State
    1
    1
    subscribe
    getState

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

  72. React
    +

    View Slide

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

    View Slide

  74. Reducer
    State
    Actions
    React
    Redux

    View Slide

  75. React
    Redux
    React
    Application

    View Slide

  76. React
    Redux
    React
    Application
    Provider

    View Slide

  77. Component
    React
    Redux
    React
    Application
    Provider
    connect
    State
    Action
    Creators

    View Slide

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

    View Slide

  79. const MyApp = () => (

    -
    0
    +

    );

    View Slide

  80. import React from 'react';
    import { render } from 'react-dom';
    import { Provider } from 'react-redux';
    render((



    ), document.getElementById('main'));

    View Slide

  81. import React from 'react';
    import { render } from 'react-dom';
    import { Provider } from 'react-redux';
    render((



    ), document.getElementById('main'));

    View Slide

  82. import React from 'react';
    import { render } from 'react-dom';
    import { Provider } from 'react-redux';
    render((



    ), document.getElementById('main'));

    View Slide

  83. 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);

    View Slide

  84. 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);

    View Slide

  85. 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);

    View Slide

  86. 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);

    View Slide

  87. 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);

    View Slide

  88. const MyApp = (props) => (


    -

    {props.counter}

    +


    );

    View Slide

  89. const MyApp = (props) => (


    -

    {props.counter}

    +


    );
    Store state
    mapStateToProps

    View Slide

  90. const MyApp = (props) => (


    -

    {props.counter}

    +


    );
    Bound action creators
    mapDispatchToProps

    View Slide

  91. Immutable
    Object State

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

  98. 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;
    }
    }

    View Slide

  99. 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;
    }
    }

    View Slide

  100. 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;
    }
    }

    View Slide

  101. 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;
    }
    }

    View Slide

  102. 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;
    }
    }

    View Slide

  103. 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;
    }
    }

    View Slide

  104. 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' } }

    View Slide

  105. 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' } }

    View Slide

  106. 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' } }

    View Slide

  107. function reducer(state = initialState, action) {
    }

    View Slide

  108. Reducer
    Composition
    Create modular reducers for
    better organization and
    readability

    View Slide

  109. Root
    Reducer
    Counter
    Reducer
    Car
    Reducer

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

  121. Root
    Reducer
    Counter
    Reducer
    Car
    Reducer
    Engine
    Reducer
    Tire
    Reducer
    … …

    View Slide

  122. Root
    Reducer
    Counter
    Reducer
    Car
    Reducer
    Engine
    Reducer
    Tire
    Reducer
    … …

    View Slide

  123. Root
    Reducer
    Counter
    Reducer
    Car
    Reducer
    Engine
    Reducer
    Tire
    Reducer
    … …

    View Slide

  124. Interact
    with APIs?

    View Slide

  125. Middleware
    Enhance Redux applications

    View Slide

  126. • Logging
    Middleware
    Enhance Redux applications

    View Slide

  127. • Logging
    • Debugging
    Middleware
    Enhance Redux applications

    View Slide

  128. • Logging
    • Debugging
    • API interaction
    Middleware
    Enhance Redux applications

    View Slide

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

    View Slide

  130. Reducer
    View
    State
    Actions
    Middleware

    View Slide

  131. Reducer
    View
    State
    Actions
    Middleware
    Intercept

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

  141. 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' } }

    View Slide

  142. 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' } }

    View Slide

  143. 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' } }

    View Slide

  144. 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' } }

    View Slide

  145. 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' } }

    View Slide

  146. const initialState = {
    users: [],
    isFetching: false,
    };

    View Slide

  147. function reducer(state = initialState, action) {
    switch (action.type) {
    case 'REQUEST_USERS':
    return { ...state, isFetching: true };
    case 'RECEIVE_USERS':
    return {
    ...state,
    isFetching: false,
    users: action.payload,
    };
    default:
    return state;
    }
    }

    View Slide

  148. function reducer(state = initialState, action) {
    switch (action.type) {
    case 'REQUEST_USERS':
    return { ...state, isFetching: true };
    case 'RECEIVE_USERS':
    return {
    ...state,
    isFetching: false,
    users: action.payload,
    };
    default:
    return state;
    }
    }

    View Slide

  149. function reducer(state = initialState, action) {
    switch (action.type) {
    case 'REQUEST_USERS':
    return { ...state, isFetching: true };
    case 'RECEIVE_USERS':
    return {
    ...state,
    isFetching: false,
    users: action.payload,
    };
    default:
    return state;
    }
    }

    View Slide

  150. const requestUsers = () => ({
    type: 'REQUEST_USERS',
    });
    const receiveUsers = users => ({
    type: 'RECEIVE_USERS',
    payload: users,
    });

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

  155. function fetchUsers() {
    return dispatch => {
    dispatch(requestUsers());
    return axios.get('/users')
    .then(({ data }) => {
    dispatch(receiveUsers(data));
    });
    };
    }
    store.dispatch(fetchUsers());

    View Slide

  156. function fetchUsers() {
    return dispatch => {
    dispatch(requestUsers());
    return axios.get('/users')
    .then(({ data }) => {
    dispatch(receiveUsers(data));
    });
    };
    }
    store.dispatch(fetchUsers());
    Action Creator

    View Slide

  157. function fetchUsers() {
    return dispatch => {
    dispatch(requestUsers());
    return axios.get('/users')
    .then(({ data }) => {
    dispatch(receiveUsers(data));
    });
    };
    }
    store.dispatch(fetchUsers());
    Action

    View Slide

  158. function fetchUsers() {
    return dispatch => {
    dispatch(requestUsers());
    return axios.get('/users')
    .then(({ data }) => {
    dispatch(receiveUsers(data));
    });
    };
    }
    store.dispatch(fetchUsers());

    View Slide

  159. Alternatives for async code.

    View Slide

  160. • Appropriate for more complex business logic
    and async flows.
    Alternatives for async code.

    View Slide

  161. • Appropriate for more complex business logic
    and async flows.
    • Middleware-based like thunk middleware.
    Alternatives for async code.

    View Slide

  162. • Appropriate for more complex business logic
    and async flows.
    • Middleware-based like thunk middleware.
    • redux-saga
    Alternatives for async code.

    View Slide

  163. • Appropriate for more complex business logic
    and async flows.
    • Middleware-based like thunk middleware.
    • redux-saga
    • redux-observable
    Alternatives for async code.

    View Slide

  164. • Appropriate for more complex business logic
    and async flows.
    • Middleware-based like thunk middleware.
    • redux-saga
    • redux-observable
    • redux-logic
    Alternatives for async code.

    View Slide

  165. ×
    ✓ Testing

    View Slide

  166. 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!

    View Slide

  167. 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.

    View Slide

  168. function fetchUsers() {
    return dispatch => {
    dispatch(requestUsers());
    return axios.get('/users')
    .then(({ data }) => {
    dispatch(receiveUsers(data));
    });
    };
    }
    However, you should test async
    action creators.

    View Slide

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

    View Slide

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

    View Slide

  171. it('fetches users', () => {
    // Arrange
    const store = createStore(reducer, applyMiddleware(thunkMiddleware));
    td.replace(axios, 'get');
    td.when(axios.get('/users')).thenResolve({ data: 'success' });
    // Act
    const promise = store.dispatch(fetchUsers());
    const subject = store.getState;
    // Assert
    expect(subject()).toEqual({ isFetching: true, users: [] });
    return promise.then(() => {
    expect(subject()).toEqual({ isFetching: false, users: 'success' });
    });
    });

    View Slide

  172. it('fetches users', () => {
    // Arrange
    const store = createStore(reducer, applyMiddleware(thunkMiddleware));
    td.replace(axios, 'get');
    td.when(axios.get('/users')).thenResolve({ data: 'success' });
    // Act
    const promise = store.dispatch(fetchUsers());
    const subject = store.getState;
    // Assert
    expect(subject()).toEqual({ isFetching: true, users: [] });
    return promise.then(() => {
    expect(subject()).toEqual({ isFetching: false, users: 'success' });
    });
    });

    View Slide

  173. it('fetches users', () => {
    // Arrange
    const store = createStore(reducer, applyMiddleware(thunkMiddleware));
    td.replace(axios, 'get');
    td.when(axios.get('/users')).thenResolve({ data: 'success' });
    // Act
    const promise = store.dispatch(fetchUsers());
    const subject = store.getState;
    // Assert
    expect(subject()).toEqual({ isFetching: true, users: [] });
    return promise.then(() => {
    expect(subject()).toEqual({ isFetching: false, users: 'success' });
    });
    });

    View Slide

  174. it('fetches users', () => {
    // Arrange
    const store = createStore(reducer, applyMiddleware(thunkMiddleware));
    td.replace(axios, 'get');
    td.when(axios.get('/users')).thenResolve({ data: 'success' });
    // Act
    const promise = store.dispatch(fetchUsers());
    const subject = store.getState;
    // Assert
    expect(subject()).toEqual({ isFetching: true, users: [] });
    return promise.then(() => {
    expect(subject()).toEqual({ isFetching: false, users: 'success' });
    });
    });

    View Slide

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

    View Slide

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

    View Slide