Fluxxor.StoreWatchMixin
is a simple React mixin that assists with watching for "change"
events on one or more stores. Normally, you'd need to bind to store change events in componentDidMount
and unbind them in componentWillUnmount
to keep from leaking memory. Additionally, you'd need to set up handlers to pull data from the stores during change events and lifecycle hooks (such as getInitialState
).
StoreWatchMixin
simply requires that you:
getStateFromFlux
that returns an object representing the part of the component's state that comes from the Flux stores.prop
or context
property named flux
that points to the Flux
instance with the stores. This is automatic if you use FluxMixin
.The mixin will then automatically
"change"
events for each store when the component mounts"change"
events when the component unmountssetState
with the return value of getStateFromFlux
when a store emits a "change"
eventgetStateFromFlux
when the component mounts (note that this object is merged with any other getInitialState
functions defined on the component or other mixins)Note that StoreWatchMixin
binds events in componentDidMount
and not componentWillMount
in order to prevent memory leaks when rendering React components that use Fluxxor on the server using Node.js. This means that actions fired from componentWillMount
that result in "change"
events in your stores will not update the component; consider moving such actions to componentDidMount
instead.
Example:
var React = require("react"),
Fluxxor = require("fluxxor"),
FluxMixin = Fluxxor.FluxMixin(React), // or window.React, etc.
StoreWatchMixin = Fluxxor.StoreWatchMixin;
var MyStore = Fluxxor.createStore({ ... }),
OtherStore = Fluxxor.createStore({ ... });
var stores = {
MyStore: new MyStore(),
OtherStore: new OtherStore()
};
var actions = { ... };
var flux = new Fluxxor.Flux(stores, actions);
var MyComponent = React.createClass({
mixins: [FluxMixin, StoreWatchMixin("MyStore", "OtherStore")],
getStateFromFlux: function() {
var flux = this.getFlux();
return {
stateFromMyStore: flux.store("MyStore").getSomeData(),
stateFromOtherStore: flux.store("OtherStore").getMoreData(),
};
},
render: function() {
// ...
}
});