Last active
December 1, 2018 01:04
-
-
Save k1r0s/be41597d9dbe3a8a4ebcaa1131f6a29b to your computer and use it in GitHub Desktop.
render functional components with self 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
import { h, patch } from "superfine"; | |
const stateful = (comp) => (props) => h("state", { | |
oncreate: (element) => { | |
const statefine = element.$$statefine = {}; | |
statefine.state = {}; | |
statefine.currentProps = props; | |
statefine.selfRender = app(comp, element); | |
statefine.setState = ss => setTimeout(() => statefine.selfRender(statefine.currentProps, statefine.state = ss({ ...statefine.state }), statefine.setState)); | |
statefine.selfRender(props, { ...statefine.state }, statefine.setState); | |
}, | |
onupdate: (element) => { | |
const statefine = element.$$statefine; | |
statefine.selfRender(statefine.currentProps = props, { ...statefine.state }, statefine.setState); | |
} | |
}) | |
const DummyComponent = props => ( | |
<div> | |
<h1>{props.count}</h1> | |
<button onclick={() => render(props.count - 1)}>-</button> | |
<button onclick={() => render(props.count + 1)}>+</button> | |
</div> | |
) | |
const CleverComponent = stateful((props, state, setState) => ( | |
<div oncreate={() => setState(() => ({ count: 0 }))}> | |
<h1>props: {props.count}</h1> | |
<h1>state: {state.count}</h1> | |
<button onclick={() => setState(s => ({ count: s.count - 1 }))}>-</button> | |
<button onclick={() => setState(s => ({ count: s.count + 1 }))}>+</button> | |
</div> | |
)); | |
const Main = GLOBAL_STATE => ( | |
<div> | |
<DummyComponent count={GLOBAL_STATE}/> | |
<hr/> | |
<CleverComponent count={GLOBAL_STATE}/> | |
<hr/> | |
<CleverComponent count={GLOBAL_STATE}/> | |
</div> | |
); | |
const app = (view, container, node) => (...args) => node = patch(node, view(...args), container) | |
const render = app(Main, document.querySelector("#app")); | |
render(0); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment