by czechdeveloper · 6y ago · 0 comments
The lack of lifecycle events in v2 complicates things a great deal for seemingly no reason. Subscriptions and Events are similar enough that they could have become a single thing, instead of having two highly similar but not-quite-the-same things to grok. The tuple syntax it uses is very strange coming from v1.
I wish I could call it a strict upgrade instead of saying "some things are worse, but other things are better."
I can tell you that Hyperapp is not for everyone. If you want to write pure, immutable, functional JavaScript and think hard about client side app architecture (unidirectional state management, controlled side effects, toggleable subscriptions), then you'll love it. I also suggest looking at Elm while you're at it.
If you are looking for a more accommodating, meet-in-the-middle kind of approach where you can mix programming styles, you might be better served by, say, P/React.
(the function 'update' in the code below)
app({
init: 0,
view: state =>
h("div", {}, [
h("h1", {}, state),
h("button", { onclick: (state, event, update) => {
window.setTimeout(() => update(state => state - 1), 1000);
} }, "subtract"),
h("button", { onclick: state => state + 1 }, "add")
]),
node: document.getElementById("app")
}) import { h, app } from "hyperapp"
import { delay } from "@hyperapp/time"
const Decrement = (state) => state - 1
app({
init: 0,
view: (state) =>
h("div", {}, [
h("h1", {}, state),
h("button", {
onclick: (state/*, event*/) => [state, delay(100, Decrement)],
}, "subtract"
),
h("button", { onclick: (state) => state + 1 }, "add"),
]),
node: document.getElementById("app"),
})
See how you never actually called setTimeout as that would be a side effect.Instead, we have "controlled effects" in Hyperapp. This `delay` function doesn't even call setTimeout itself, but return an object that tells Hyperapp how. Just like how `h("button")` or `<button>` with JSX doesn't actually create a button, but an object representation of it.
Finally this part: [state, delay(100, Decrement)], only placed here for convenience (as you'll usually want that in its own action) is how you tell Hyperapp to do the effect when the button is clicked. This is the same (model Cmd) continuation pattern used in Elm.