Created
July 10, 2019 13:28
-
-
Save sergey-shpak/dea3d6f70133bc53d11ff6a39fd58727 to your computer and use it in GitHub Desktop.
Hyperapp#2 immutable state
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict' // Strict mode to throw mutation errors | |
import { h, app } from 'hyperapp' | |
import { immutable } from 'helpers' | |
// action that is trying to mutate the state | |
// will throw error for any mutation | |
const onclick = state => { | |
++state.counter | |
return state | |
} | |
app({ | |
init: { counter: 0 }, | |
view: state => h('div', {}, [ | |
h('span', {}, state.counter), | |
h('button', { onclick }, 'try to mutate!') | |
]), | |
node: document.body | |
}, immutable) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const freeze = obj => { | |
obj && Object.getOwnPropertyNames(obj).forEach(name => | |
typeof obj[name] == 'object' && freeze(obj[name])) | |
return Object.freeze(obj) | |
} | |
export default dispatch => | |
(action, props, obj) => dispatch( | |
typeof action == 'object' && !Array.isArray(action) | |
? freeze(action) | |
: action, | |
props, | |
obj | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment