DEV Community

Mykolas Mankevicius
Mykolas Mankevicius

Posted on • Edited on

1

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!

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →