rx-store
v1.0.0
Published
Reactive library for managing state
Downloads
17
Maintainers
Readme
rx-store
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.
Installation
npm install --save rx-store
Usage
Import library
ES6
import {createRxStore} from 'rx-store';
ES5 with modules
var createRxStore = require('rx-store').createRxStore;
ES5
<script src="node_modules/rx-store/dist/rx-store.browser.min.js"></script>
// window.RxStore.createRxStore
Create a store
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);
Subscribe to State Changes
store.subscribe(function(state) {
// do stuff with state
});
// which is equivalent to
store.state$.subscribe(function(state) {
// do stuff with state
});
Modify State
var action = 4;
store.dispatch(action);
store.subscribe(function(state) {
console.log('State: ' + state);
});
// State: 0
// State: 4
Modify State from Browser Event
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);
});
Using as a Flux Pattern
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
};
}
var addAction = add(4);
var addAction2 = add(-1);
store.dispatch(addAction);
store.dispatch(addAction2);
store.subscribe(function(data) {
console.log(data);
});
// {count: 0, somethingElse: 'data'}
// {count: 4, somethingElse: 'data');
// {count: 3, somethingElse: 'data');
Using with React Views
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);