Redux Thunk

Redux Thunk middleware allows you to write action creators that return a function instead of an action. The thunk can be used to delay the dispatch of an action, or to dispatch only if a certain condition is met.

install

npm install redux-thunk
npm install redux-logger // logs when action is dispatched in developer tool console

store.js

import thunk from 'redux-thunk';

const middleWares = [];

// use logger middleware when in development mode
if (process.env.NODE_ENV === 'development') {
    middleWares.push(logger);
}

const store = createStore(rootReducer, applyMiddleware(...middleWares));

hoge.actionTypes.js

const HogeActionTypes = {
    FETCH_HOGE_START: `FETCH_HOGE_START`,
    FETCH_HOGE_SUCCESS: 'FETCH_HOGE_SUCCESS',
    FETCH_HOGE_FAILURE: 'FETCH_HOGE_FAILURE',
};

export default HogeActionTypes;

hoge.actions.js

import HogeActionTypes from ‘HogeActionTypes.js’

export const fetchHogeSuccess = (hoge) => ({
    type: HogeActionTypes.FETCH_HOGE_SUCCESS,
    payload: hoge,
});

export const fetchHogeFailure = (error) => ({
    type: HogeActionTypes.FETCH_HOGE_FAILURE,
    payload: error,
});

export const fetchHogeStart = () => ({
    type: HogeActionTypes.FETCH_HOGE_START,
});

export const fetchHogeStartAsync = () => {
    return (disptach, getState) => {
    dispatch(fetchHogeStart)();
    fetchHoge()
        .then((hoge) => { dispatch(fetchHogeSuccess(hoge)); })
        .catch((error) => { dispatch(fetchHogeFail(error)); } )
   }    
}

hoge.reducers.js

import HogeActionTypes from ‘HogeActionTypes.js’

const INITIAL_STATE = {
    hoge: null,
    isFetching: false,
    errorMessage: undefined,
};

const hogeReducer = (state = INITIAL_STATE, action) => {
    switch (action.type) {
        case HogeActionTypes.FETCH_HOGE_START:
            return {
                ...state,
                isFetching: true,
            };

        case HogeActionTypes.FETCH_HOGE_SUCCESS:
            return {
                ...state,
                isFetching: false,
                hoge: action.payload,
            };

        case HogeActionTypes.FETCH_HOGE_FAILURE:
            return {
                ...state,
                isFetching: false,
                errorMessage: action.payload,
            };

        default:
            return state;
    }
};

export default hogeReducer;

hoge.js

import { fetchHogeStartAsync } from ‘hoge.actions.js’

const fetchHoge = () => {
    fetchHogeStartAsync();
}


const mapDispatchToProps = (dispatch) => ({
    fetchHogeStartAsync: () => dispatch(fetchHogeStartAsync()),
})