I’ve run into a situation in this app I’m working on where I really need to have certain objects at the highest level (such as a modal component) that other components anywhere in the hierarchy can call upon. I don’t really understand how Flux and Redux work, despite looking at the documentation—or I should say, I don’t understand how to make it work in the context of Meteor. So I thought, why can’t I just make my own really simple global Store object?
I tried it, and it seems to work just fine. What I’m doing is creating a mixin that I use in my main Layout
component, which provides all the global actions. So for instance:
Layout = React.createClass({
mixins: [ReactMeteorData, GlobalActions],
componentWillMount() {
Store = this;
},
And then:
Store = {};
GlobalActions = {
getDefaultProps() {
return {
actions: {
showModal(message, buttons, callback) {
Store.setState({
modalMessage: message,
modalButtons: buttons,
modalVisible: true,
modalCallback: callback
});
}
}
}
},
getInitialState() {
return {
modalButtons: ['OK'],
modalMessage: '',
modalVisible: false,
}
}
};
And then in Layout
at the bottom of render()
:
<Modal visible={this.state.modalVisible}
message={this.state.modalMessage}
buttons={this.state.modalButtons}
callback={this.state.modalCallback} />
So then any component, no matter where it is, can do something like this:
this.props.actions.showModal(
'Some message.',
['OK'],
this.userClickedBtn
);
Oh and last but not least, this is the Modal
's button click handler:
handleButtonClick(buttonLabel) {
this.props.callback.call(null, buttonLabel);
Store.setState({modalVisible: false});
},
After all, it looks like Flux and its relatives are sort of doing the same thing, just creating a global store. So is there anything wrong with this approach, then? I just don’t think I have the time to dedicate to learning Flux or Redux. Maybe if there a neat/clean Meteor package that bundled up Redux and made it super simple to use, I might go that route. But in the mean time, my semi-hacky solution seems to do the trick. Unless there are potential gotchas?