mobile menu icon

Dependency Injection in Redux

Published by Carlos Blé on 05/04/2017

React, Redux, JavaScript


Redux provides a function called connect that binds the component to the store. This is the place where state and actions are map to component properties and also where the component subscribes to changes in the store. Well, the subscription happens as long as React’s Provider is in place:

We invoke connect from our component factory. An example:

The production code would import ProfilePage - last line. Tests will import and use createProfilePage in order to inject test doubles to mock the API and other dependencies like the notifier - a simple wrapper around an alert dialog. The first connect argument is the function that maps the global state to the component’s state. The second argument makes actions available to the component. We distinguish two kind of actions. Those that impact on the state and those which don’t. If the action is going to be processed by a reducer that in turn is going to change the state, then a call to dispatch is needed - lines 18 & 24. In fact those functions are action creators, they return an object or another function to be dispatched asynchronously with the help of thunk middleware. Function dispatch is provided by Redux, like connect. On the other hand if the action does not alter the state of the frontend app, we just invoke it and return it’s result, which is typically a promise - line 21. We are not using the helper function bindActionCreators from Redux to make it explicit where we need its machinery and where we don’t

In both cases, closures hide the fact that actions require the serverApi to work, making its usage simpler for the component - the consumer. ProfilePage component will invoke the action like this:

I am far from being a Redux expert and I guess some people will find it unusual to not call dispatch every time. Notice that saveProfile is not an action creator but just a function that return a promise. However I find this code simpler, I don’t see the point in going through a reducer when the state is not going to be changed.

Actions and action creators:

Given this factory, in the next blog post I’ll explain how we test-drive the app from the outside-in, as well as the various kind of tests.

Volver a posts