Dependency Injection in a redux action creator

React-thunk supports passing an arbitrary object to a thunk using withExtraArgument. You can use this to dependency-inject a service object, e.g.:

const bluetoothService = require('./blueToothService');

const services = {
    bluetoothService: bluetoothService
};

let store = createStore(reducers, {},
    applyMiddleware(thunk.withExtraArgument(services))
);

Then the services are available to your thunk as a third argument:

function startDeviceScan() {
    return function (dispatch, getstate, services) {
        // ...
        services.bluetoothService.startDeviceSearch((device) => {
            dispatch(addDevice(device));
        });
    }
}

This is not as formal as using a dependency-injection decorator in Angular2 or creating a separate Redux middleware layer to pass services to thunks—it’s just an “anything object” which is kind of ugly—but on the other hand it’s fairly simple to implement.

Leave a Comment

techhipbettruvabetnorabahisbahis forumu