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 style="display: flex">
<div style="width: 50%">
<div>
<p>Type here...</p>
<input type="text" value="shane" id="input">
<p>User state</p>
<pre><code id="userelem"></code></pre>
</div>
<hr>
<div>
<p>Click this button</p>
<button type="button" id="button">Toggle</button>
<pre><code id="globalelem"></code></pre>
</div>
</div>
<div style="width: 50%">
Full state tree
<pre><code id="globalstate"></code></pre>
</div>
</div>
JavaScript
// user reducer
function userReducer (user, action) {
switch(action.type) {
case 'USER_NAME':
return user.set('name', action.payload);
default: return user;
}
}
// global reducer
function globalReducer (global, action) {
switch(action.type) {
case 'GLOBAL_AUTH':
return global.update('auth', auth => !auth); // flip
default: return global;
}
}
// initial data
const initial = {
user: {name: 'shane'},
global: {auth: false}
};
const store = staunch.createStore(initial, {
user: userReducer,
global: globalReducer
});
// dom elements for rendering
const userElem = document.querySelector('#userelem');
const globalElem = document.querySelector('#globalelem');
const globalState = document.querySelector('#globalstate');
// input handler, dispatches an action when input received
document.querySelector('input').addEventListener('input', function(e) {
store.dispatch({type: 'USER_NAME', payload: e.target.value});
});
// button handler, dispatches an action when clicked
document.querySelector('button').addEventListener('click', function(e) {
store.dispatch({type: 'GLOBAL_AUTH'});
});
// helper to convert state to formatted JSON (demo only)
const json = (x) => JSON.stringify(x, null, 2);
// create a stream of user state changes
store.changes('user')
.map(json)
.subscribe(string => userElem.innerHTML = string);
// create a stream of global state changes
store.changes('global')
.map(json)
.subscribe(string => globalElem.innerHTML = string);
// create a stream of global state changes
store.changes()
.map(json)
.subscribe(string => globalState.innerHTML = string);