Skip to content

Instantly share code, notes, and snippets.

@sergey-shpak
Created July 10, 2019 13:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sergey-shpak/dea3d6f70133bc53d11ff6a39fd58727 to your computer and use it in GitHub Desktop.
Save sergey-shpak/dea3d6f70133bc53d11ff6a39fd58727 to your computer and use it in GitHub Desktop.
Hyperapp#2 immutable state
'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)
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