Last active
December 3, 2018 09:39
-
-
Save okwolf/d38773ae51c0837ba73dad1e3e348b83 to your computer and use it in GitHub Desktop.
Update an existing Hyperapp: https://codepen.io/okwolf/pen/ppdpgj?editors=0010
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
import { h, app } from "hyperapp" | |
// higher-order app function for update powers | |
const withUpdateApp = nextApp => { | |
return (initialState, actionsTemplate, view, container) => { | |
let currentView = view | |
const enhancedActions = nextApp( | |
initialState, | |
{ | |
...actionsTemplate, | |
runAction: ({ action, data }) => state => { | |
const result = action(data) | |
return typeof result === "function" | |
? result(state, enhancedActions) | |
: result | |
}, | |
updateApp: ({ state = {}, actions = {}, view = currentView }) => { | |
Object.keys(actions).forEach(name => { | |
Object.assign(enhancedActions, { | |
[name]: data => | |
enhancedActions.runAction({ action: actions[name], data }) | |
}) | |
}) | |
currentView = view | |
return state | |
} | |
}, | |
(state, actions) => currentView(state, actions), | |
container | |
) | |
return enhancedActions | |
} | |
} | |
// Compose with app | |
const main = withUpdateApp(app)(state, actions, view, document.body) | |
// Use with updated state, actions, and/or view | |
main.updateApp({ | |
state: { | |
// new state values from here will be merged in | |
}, | |
actions: { | |
// these actions will be added/overridden | |
}, | |
view: { | |
// optional new view function to use | |
} | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
It is awesome. Thanks for your suggestions.