DEV Community

Thomas Reggi
Thomas Reggi

Posted on

A Server - Client JS Serialization Approach

Given that Next.js Server Actions and TRPC are gaining traction as approaches that utilize code-splitting, javascript serialization, and fetch calls I thought I'd document a way I approached this in my library HTMX Components, as I revisit the library and ponder whether this is the best way to achieve this.

HTMX Components is a Deno server for serving HTMX compliant front-end code, handling routing, code splitting and bundling.

We're going to be looking at and breaking down one piece of code and focusing on just the serialization part.

const { component, partial, serve, bundleImport, routes } = new HTMXComponents('@reggi/delete-row')
export const EditOne = await bundleImport('./client_code/edit_one.ts')

const DumbRow = ({ data }: { data: any }) => (
  <tr>
    <td>{data.firstName} {data.lastName}</td>
    <td>{data.email}</td>
    <td>
      <EditRow.button.get onclick={EditOne.onClickEdit(THIS_ELEMENT, EVENT)} identifier={data.id}>Edit</EditRow.button.get>
    </td>
  </tr>
)
Enter fullscreen mode Exit fullscreen mode

I'm doing some special stuff with bundleImport, think of it as a custom dynamic import. ./client_code/edit_one.ts is the client code file we'd like to include with this code, meaning we want to 1) bundle the code with any imported dependencies and 2) convert the code from TS to JS. We also return EditOne fully typed as it is in that file, there are no changes to that typing. We then call the .onCLickEdit function in the onclick handler EditOne.onClickEdit(THIS_ELEMENT, EVENT). Note this is server-side JSX it's not onClick because we're on the server, onclick, like within the DOM takes a string. So what do we need the value of EditOne.onClickEdit(THIS_ELEMENT, EVENT) to return? A reference to itself! Literally just that string edit_one.onClickEdit(this,event)!

Anyway this is one way to do serialization that I thought was interesting and wanted to document. There's examples in the repo for more info!

Top comments (0)