rx-store
is a reactive solution for managing state. It is framework and view agnostic, though it can be used as the basis for a Flux pattern.
npm install --save rx-store
import {createRxStore} from 'rx-store';
var createRxStore = require('rx-store').createRxStore;
<script src="node_modules/rx-store/dist/rx-store.browser.min.js"></script>
// window.RxStore.createRxStore
createRxStore
takes a reduce function as an argument as well as an optional initial state. If not specified the initial state starts out as undefined. Note that the state can be any valid JS type (object, array, number, etc.).
function sum(previousState, nextState) {
return previousState + nextState;
}
var initialState = 0;
var store = createRxStore(sum, initialState);
store.subscribe(function(state) {
// do stuff with state
});
// which is equivalent to
store.state$.subscribe(function(state) {
// do stuff with state
});
store.subscribe(function(state) {
console.log('State: ' + state);
});
var action = 4;
store.dispatch(action);
// logs:
// State: 0
// State: 4
var addTwo$ = Rx.Observable.fromEvent(btnNode, 'click').map(e => {
return 2;
});
// send each new action to the store
addTwo$.subscribe(function(action) {
store.dispatch(action);
});
function reducer(state, action) {
switch (action.type) {
case 'ADD':
var addState = state;
addState.count += action.payload;
return addState;
case 'ACTION_TWO':
return actionTwo(state);
default:
return state;
}
}
var initialState = {count: 0, somethingElse: 'data'};
var store = createRxStore(reducer, initialState);
function add(data) {
return {
type: 'ADD',
payload: data
};
}
store.subscribe(function(data) {
console.log(data);
});
var addAction = add(4);
var addAction2 = add(-1);
store.dispatch(addAction);
store.dispatch(addAction2);
// logs:
// {count: 0, somethingElse: 'data'}
// {count: 4, somethingElse: 'data');
// {count: 3, somethingElse: 'data');
class MyComponent extends React.Component {
componentDidMount() {
this.countSubscription = this.props.countStream.subscribe((count) => {
this.setState({count: count});
});
}
componentWillUnmount() {
this.countSubscription.unsubscribe();
}
render() {
return <div>{this.state.count}</div>;
}
}
var count$ = store.state$.map(function(data) {
return data.count;
});
ReactDOM.render(<MyComponent countStream={count$} />, domNode);