proxy-store
v1.0.8
Published
Save react state to javascript store built with es2015 proxy
Downloads
5
Maintainers
Readme
How to use.
First install npm package
npm i --save proxy-store
import necessary files on top of your javascript file.
import createStore from "proxy-store";
Now lets create new storage.
For that create an object that will be the state of your app, for example a todos app minimal state would look like this
let data = {
name:"random",
todos:[
{ name:"walk dog", date:"today", done:true },
{ name:"buy food", date:"tomorrow", done:false }
]
};
Then create new store with this data
let store = new createStore(data);
Add observer decorator to React Component
@store.observer class MyComponent extends Component
Now all the data that you created in you object can be reached from you app with props like this
<span>{this.props.name}</span>
But to get data from array you must use Array.from(this.props.todos)
,
because some why proxy makes the array into object, maybe this can be fixed soon.
For example you are trying to map and show the todos list you need to use it like this
{ Array.from(this.props.todos).map((item, index) => {
return <div onClick={this.toggleTodo.bind(this, item.name )} key={index} className={`todo ${item.done ? "done" : ""}` }>
<span>{item.name}</span>
<span>{item.date}</span>
</div>
})
}
If you want to apply changes to react stateless function use observer like function
const component = (props) => {
return <div>
<h2>{props.name}</h2>
</div>
}
export default store.observer(component);
Make changes to store
To update store simple use the store like regular javascript object, but use store.data
For example
store.data.name = "Steve"
Updates observed components this.props.name
to "Steve"
See example here
https://github.com/tonis2/react-proxy-store
Much inspiration got from mweststrate-s mobx, https://github.com/mobxjs/mobx