Files

28 lines
618 B
JavaScript
Raw Permalink Normal View History

import { Component } from "preact"
2022-10-26 13:11:51 +08:00
export const Stateful = ({ getInitialState, handlers, render }) => {
2022-10-26 13:11:51 +08:00
return class extends Component {
constructor() {
super()
this.compState = getInitialState()
this.handlers = Object.fromEntries(
Object.entries(handlers).map(([name, h]) => [
name,
this.makeHandler(h),
]),
2022-10-26 13:11:51 +08:00
)
}
makeHandler(h) {
return (...args) => {
this.compState = h(this.compState, ...args)
this.forceUpdate()
}
}
render() {
return render(this.props, this.compState, this.handlers)
}
}
}