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!

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read more →

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs