async calls WIP

This commit is contained in:
Dmitry Vasilev
2022-10-26 13:11:51 +08:00
parent a78ba0fa78
commit c3365fe1ee
8 changed files with 112 additions and 19 deletions

View File

@@ -0,0 +1,23 @@
/* external */
import {h, render} from 'https://unpkg.com/preact?module';
/* external */
import {Stateful} from './stateful.js'
const Counter = Stateful({
getInitialState: () => ({counter: 0}),
handlers: {
inc: ({counter}) => ({counter: counter + 1}),
dec: ({counter}) => ({counter: counter - 1}),
},
render: (props, state, handlers) =>
h('div', null,
h('span', null, state.counter),
h('button', {onClick: handlers.inc}, 'Increment'),
h('button', {onClick: handlers.dec}, 'Decrement'),
)
})
render(h(Counter), globalThis.document.body)

View File

@@ -0,0 +1,31 @@
import {Component} from 'https://unpkg.com/preact?module';
export const Stateful = ({getInitialState, handlers, render}) => {
return class extends Component {
constructor() {
super()
this.compState = getInitialState()
this.handlers = Object.fromEntries(
Object
.entries(handlers)
.map(([name, h]) =>
[name, this.makeHandler(h)]
)
)
}
makeHandler(h) {
return (...args) => {
this.compState = h(this.compState, ...args)
this.forceUpdate()
}
}
render() {
return render(this.props, this.compState, this.handlers)
}
}
}