Dependency Injection in a redux action creator. You can use a redux middleware that will respond to an async action. In this way you can inject whatever service or mock you need in a single place, and the app will be free of any api implementation details:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 | // bluetoothAPI Middleware import bluetoothService from 'bluetoothService'; export const DEVICE_SCAN = Symbol('DEVICE_SCAN'); // actions creation helper for the middleware const createAction = (type, payload) => ({ type, payload }); // This is the export that will be used in the applyMiddleware method export default store => next => action => { const blueToothAPI = action[DEVICE_SCAN]; if(blueToothAPI === undefined) { return next(action); } const [ scanDeviceRequest, scanDeviceSuccess, scanDeviceFailure ] = blueToothAPI.actionTypes; next(createAction(scanDeviceRequest)); return new Promise((resolve, reject) => bluetoothService.startDeviceSearch((device) => resolve(device), (error) = reject(error)) .then((device) => next(createAction(scanDeviceSuccess, device))) .catch((error) => next(createAction(scanDeviceFailure, error ))); }; // Async Action Creator export const startDeviceScan = (actionTypes) => ({ [DEVICE_SCAN]: { actionTypes } }); // ACTION_TYPES export const SCAN_DEVICE_REQUEST = 'SCAN_DEVICE_REQUEST'; export const SCAN_DEVICE_SUCCESS = 'SCAN_DEVICE_SUCCESS'; export const SCAN_DEVICE_FAILURE = 'SCAN_DEVICE_FAILURE'; // Applying the bluetoothAPI middleware to the store import { createStore, combineReducers, applyMiddleware } from 'redux' import bluetoothAPI from './bluetoothAPI'; const store = createStore( reducers, applyMiddleware(bluetoothAPI); ); // Usage import { SCAN_DEVICE_REQUEST, SCAN_DEVICE_SUCCESS, SCAN_DEVICE_FAILURE } from 'ACTION_TYPES'; dispatch(startDeviceScan([SCAN_DEVICE_REQUEST, SCAN_DEVICE_SUCCESS, SCAN_DEVICE_FAILURE])); |
If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.