Better LiveView Hooks with Typescript
Mykolas Mankevicius

Mykolas Mankevicius @neophen

About: Full stack developer. Working on making complex things as simple as i can make them.

Location:
Vilnius, Lithuania
Joined:
Aug 17, 2018

Better LiveView Hooks with Typescript

Publish Date: Oct 29 '24
1 0

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!

Comments 0 total

    Add comment