React binding for modflux state management
- It runs in different environments
- ES6 as a source.
- It is tiny
React-Mflux evolves the ideas of Redux but favors an object oriented methodology that allows to build reusable stores that encapsulate the state of a specific component instead of the whole application, therefore coming back to some of the original Flux ideas
To install the stable version:
npm install --save react-mflux
This assumes you are using npm as your package manager.
React-Mflux is available as a collection of CommonJS modules. These modules are what you get when you import react-mflux
in a Webpack, Browserify, or a Node environment.
Most likely, you'll also need the React bindings
import {Store, storeManager} from 'mflux';
/**
* This is a class that extends the abstract store provided by mflux
* The actions and the reducer are encapsulated inside the store, so the client
* does not know about dispatch and the reducer, therefore encapsulating those inside the store
*/
// Extend from mflux store
class IncrementDecrementStore extends Store {
// Initial state
state = {
value: 0
};
constructor(config) {
super(config);
this.increment = this.increment.bind(this);
this.decrement = this.decrement.bind(this);
}
increment() {
this.dispatch({
type: 1
});
}
decrement() {
this.dispatch({
type: 2
});
}
reducer(action) {
switch (action.type) {
case 1: return { value: this.state.value + 1 };
case 2: return { value: this.state.value - 1 };
default: throw new Error(`Invalid action type: ${action.type}`);
}
}
}
// Instantiate the store, if you want to track the store with the store manager provide a unique identifier for that store
let store = new IncrementDecrementStore({ id: 'testStoreId' });
console.log(store.state.value) // The initial state. It should log Object {value: 0}
// Subscribe to the store
store.subscribe(state => console.log(state.value));
store.increment(); // It should log Object {value: 1}
store.decrement() // It should log Object {value: 0}