JSFiddle - React, Tailwind, and code Playground
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/4.0.6/rx.all.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/immutable/3.7.3/immutable.min.js"></script>
<script src="https://unpkg.com/staunch-store@1.0.3/dist/staunch.js"></script>
<div>
<button type="button" id="load">Load shakyshane (2 second delay)</button>
</div>
<div>
<pre><code id="debug"></code></pre></div>
JavaScript
const elem = document.querySelector('#debug');
const button = document.querySelector('#load');
// create the store
const store = staunch.createStore();
// register some state, reducers & async effects in 1 go
store.register({
state: {
// this will be converted to an Immutable.Map
user: {
loading: false,
result: null,
messages: []
}
},
reducers: {
// this function will be 'bound' the 'user' section of the state tree
// there's no need to worry about setting defaults
user: function(state, action) {
if (action.type === 'USER_FETCH') {
return state
.set('loading', true)
.set('result', null) // clear any previous
}
if (action.type === 'USER_SUCCESS') {
return state
.set('loading', false)
.set('result', action.payload)
}
return state;
}
},
// Async effects are built-in, just like redux-observable,
// but they require ZERO configuration, it will 'just work'
effects: function(action$) {
return action$.ofType('USER_FETCH')
.flatMap(({action, state}) =>
fetch('https://api.github.com/users/shakyshane')
.then(x => x.json())
)
.map(resp => {
return {
type: 'USER_SUCCESS',
payload: resp
}
})
.delay(2000) // fake delay to simulate network
}
});
// only when the 'loading' property on the user changes,
// set the button to disabled
store.changes(['user', 'loading'])
.do(x => console.log('setting', x))
.subscribe((loading) => {
button.disabled = loading;
});
// dump the state into formatted JSON
store.changes()
.map(x => JSON.stringify(x, null, 2))
.subscribe(string => elem.innerHTML =...