react-simple-state
v1.0.2
Published
a simple state manager for react projects
Downloads
12
Readme
React Simple State
A simple state manager for React projects
What this Is
An incredibly tiny and simple subscription-based state manager focused on React. You can use it outside of a React environment, but the initial intention for this was learning React. All it does is keep track of state via IDs that you set, and evokes that state out to its subscribers when the state is updated.
Getting Started
You can get started with RSM in a few easy steps:
npm install --save react-simple-state
Import and initialize the singleton (recommended outside of the component class):
import SimpleState from 'react-simple-state';
const simpleState = new SimpleState();
To add a new listener with some id (will throw an error if same id is used twice):
simpleState.addListener('someId', {
some: 'initial',
state: 'and',
theState: 'values'
});
To get the current state of some id (will throw an error if id not found):
simpleState.getState('someId');
To subscribe to state changes of some id (recommended in componentWillMount()):
simpleState.subscribe('someId', this, (nextState) => {
this.setState({
someProp: nextState
});
});
Where this
refers to the component.
To unsubscribe to state changes of some id (recommended in componentWillUnmount()):
simpleState.unsubscribe('someId', this);
Where this
refers to the component.
Example Repo
If you want to see it in action, fork the example repository: https://bitbucket.org/codingcolorado/react-simple-state-example
A Sample Component
Here's an sample of how you might use the state simpleState in a componenet (assumes the listener has been added already somewhere else in your app):
import React, { Component } from 'react';
import SimpleState from 'react-simple-state';
const simpleState = new SimpleState();
class SomeComponent extends Component {
constructor(props) {
super(props);
const user = simpleState.getState('user');
this.state = {
user: user
}
}
componentWillMount() {
simpleState.subscribe('user', this, (nextUser) => {
this.setState({
user: nextUser
});
});
}
componentWillUnmount() {
simpleState.unsubscribe('user', this);
}
render() {
return (
<div>
<ul>
<li>First: {this.state.user.first}</li>
<li>Last: {this.state.user.last}</li>
<li>Job: {this.state.user.job}</li>
</ul>
</div>
);
}
}
export default SomeComponent;