Last active
October 19, 2020 22:47
-
-
Save loganvolkers/6ba4335d0835d69a77b0b37b89589513 to your computer and use it in GitHub Desktop.
Stencil Hooks
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 { Component, h } from '@stencil/core'; | |
import { useState } from 'haunted'; | |
import { useHook } from './stencil-hooks'; | |
@Component({ | |
tag: 'example-hook', | |
}) | |
export class ExampleHook { | |
render = useHook(this, () => { | |
const [count,setCount] = useState(0); | |
return <div>Child is {count} <button onClick={()=>setCount(count+1}></button></div>; | |
}); | |
} |
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 { State } from 'haunted'; | |
import { getElement, JSX } from '@stencil/core'; | |
const StateProp = Symbol("state"); | |
export function useHook(component:unknown, hook:()=>JSX.Element|JSX.Element[]){ | |
let state = component[StateProp]; | |
if(!state){ | |
const element = getElement(component); | |
state = component[StateProp] = new State( | |
()=>element.forceUpdate(), | |
element | |
) | |
//@ts-ignore | |
const {disconnectedCallback} = component; | |
component["disconnectedCallback"] = function(){ | |
state.teardown(); | |
state = null; | |
disconnectedCallback && disconnectedCallback(); | |
} | |
} | |
return ()=>{ | |
const out = state.run(hook) | |
state.runEffects(); | |
return out; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment