DEV Community

Mykolas Mankevicius
Mykolas Mankevicius

Posted on • Edited on

Better LiveView Hooks with Typescript

Ok so sometimes you need typescript for your hooks.
And then basically you need to type every single method in the hook.
You have to do bindings in mounted so that you could use the functions in callbacks and so forth.
It becomes really tiring and verbose really quickly.

Solution?

LiveViewHook class

Link to gist

Here's a simple example of how to use it:

import { LiveViewHook } from './live_view_hook'

class HeightTrackerHook extends LiveViewHook {
  private resizeObserver: ResizeObserver | null = null

  mounted() {
    this.resizeObserver = new ResizeObserver(this.setHeightProperty)
    this.resizeObserver.observe(this.el)
  }

  beforeDestroy() {
    this.resizeObserver?.unobserve(this.el)
  }

  private setHeightProperty = ([entry]: ResizeObserverEntry[]) => {
    document.documentElement.style.setProperty(this.requiredAttr('data-height-var'), `${entry.contentRect.height}px`)
  }
}

export default HeightTrackerHook.createViewHook()
Enter fullscreen mode Exit fullscreen mode

Hope this helps!
Take care!

Top comments (0)