Basic Usage with Lit

This section provides a complete, framework-agnostic example of how to connect to the hREA backend from a user interface. We will use Lit, a simple library for building fast, lightweight web components. Because Lit is based on native Web Components, these patterns can be easily adapted to any other framework or even vanilla JavaScript.

This guide assumes you have followed the Integration Guide and have your backend configured.

1. UI File Structure

In your scaffolded project, navigate to the ui/ directory. We will create the following file structure:

ui/
├── src/
│   ├── holochain-client.ts  # Core logic for connecting to Holochain & hREA
│   ├── client-provider.ts   # A component to provide the client to the app
│   └── hrea-test.ts         # The example component with buttons and results
│   └── index.css            # Styles
├── index.html               # The main HTML file
└── ... (other config files)

2. Add Lit Dependency

If you didn't choose Lit during the scaffolding, you'll need to add it to your ui/package.json:

cd ui
npm install lit @lit-labs/context

3. The Code

Here is the full code for each of the files.

src/holochain-client.ts

This file contains the core, framework-agnostic logic for establishing the connection to Holochain and creating the Apollo GraphQL client for hREA.

src/client-provider.ts

This is a wrapper component. Its only job is to connect to Holochain and then provide the client instances to all of its child components via Lit's context API.

src/hrea-test.ts

This component consumes the context provided by <client-provider> and uses the Apollo Client to send queries and mutations to hREA.

index.html

Finally, your ui/index.html ties everything together.

4. How It Works

  1. index.html loads the <client-provider> component.

  2. client-provider.ts is rendered. Its firstUpdated lifecycle method triggers the connect() method in our HolochainConnection class.

  3. While connecting, it displays a "Connecting..." status message.

  4. Once the connection is successful, HolochainConnection creates the Apollo Client for hREA and calls the status update callback.

  5. The ClientProvider receives the 'connected' status and sets the hreaClientContext value, passing down the client instances. It then renders its <slot>, which contains the <hrea-test> component.

  6. hrea-test.ts consumes the context. Now that it has a value, it renders the UI with the buttons.

  7. When you click a button, a method like createPerson is called, which uses the this.hreaClient instance to send a GraphQL mutation.

  8. The results are added to the component's reactive results state, causing the UI to re-render and display the outcome.

Last updated