Be the first user to complete this post
|Add to List|
Automating Store and Action registration for multiple components using Fluxxor
It is very likely that when architecting your flux application, you will organize your components into different folders. Some of these components will depend on stores and actions. And for some of them, the stores and actions are shared.
The quick start guide shows you how you register actions and stores beforehand. Although its an effective strategy, its not scalable because it is difficult to identify all the stores and actions that the sub-components on a page are going to require at the time of defining the top level component, the place where your instantiate your flux object. This also implies that you would have to edit your top level component to register a new store whenever a component is added that depends on a store.
The situation gets even more complicated if you allow components to register stores by themselves at runtime because it is possible that different components might depend same store and therefore it is wise to only have one place to register a store.
If only we could have a way to allow each component to mention the stores it depends on, and then the runtime would take care of registering them if not already registered.
It seems like this is a very good use case for creating a mixin that can act as a checkpoint for components that need to register stores and actions.
Lets say that we have a simple data store as shown below.
[wpgist id="44898ab1dac0b8d5d396" file="MyDataStore.js"]
And a simple action as shown below
[wpgist id="44898ab1dac0b8d5d396" file="MyDataActions.js"]
Notice that in the last line, we assigned a displayName to the store. This is the name with which we will auto-register the store using our mixin.
We will call our mixin
FluxContextMixin since it helps in constructing the flux context by adding stores and actions as necessary.
Our objective is to use this mixin on any component that depends on other Fluxxor stores and actions. And by simply listing out the stores and actions in the statics, the mixin would automatically register them in the flux context if they were not already registered.
Below is an example of a component that would use our
[wpgist id="44898ab1dac0b8d5d396" file="MyComponent.js"]
Now comes the meat of the matter, our FluxContextMixin itself. I have added a tonne of inline comments to explain what I am trying to do at each step of the way.
Essentially, the mixin does a few things
- Using context and childContext in React
- Render a d3js Tree as a React Component
- Uncaught TypeError: Cannot read property 'toUpperCase' of undefined in React
- Require the css file of a package using webpack
- Pure vs Impure functions
- Pass props to the handler component in react-router
- webpack with babel6 and react
- Reactjs flux architecture - Visualized