Redux and the Store

A lot of examples of using Redux show it in simplistic ways — the store is created as a local constant in one module and then others access it via the JSX helpers. But what do you do when you want to access the store programmatically? It turns out to be really simple and I’ll outline how I did that. My usage case was having a module that implements a hack: the module observes a specific state and when conditions are met, it changes the state. The most likely way to implement this is to use a Redux reducer but let’s implement it without one.

When I first started using CommonJS, I had an important realization that is ultimately super simple but not everyone seems to get: a module can return a function or it can return an object. When say module A exports an object and modules B and C import (require) A, they both have a reference to the same object.

Back to Redux: the store is a singleton. There is supposed to only ever be one store and everything operates off of that store. That makes a lot of sense when you start diving into it more. But that also means we can create the store in a module and export it. So that is what I did:

import { createStore, combineReducers } from ‘redux’;
import * as reducers from ‘../reducers’;
const reducer = combineReducers(reducers);
export default createStore(reducer);

Now the observer module can import the store and dispatch on it:

import store from ‘../routes/store’;
import * as actionTypes from ‘../constants/actionTypes’;
const someName = 'abc123';
function mutateStateOnSomeCondition(someState) {
if (someState.something) {
store.dispatch({
type: actionTypes.DISABLE_X,
name: someName
});
} else {
store.dispatch({
type: columnActionTypes.ENABLE_X,
name: someName
});
}
}

There is more to the observer module but I wanted to pull out the key part of how to dispatch on a Redux store without any of the JSX helpers.

The store is imported in the same way in the main view for the application. Nothing really majored has changed. But we’ve taken advantage of how modules work to push the store out to a module that we can then use where appropriate in a way that is more flexible. As I mentioned earlier, the observer should likely be a reducer — I’ll get there soon. But in the meantime, this lets me accomplish what I need right now.

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.