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/context3. The Code
Here is the full code for each of the files.
src/holochain-client.ts
src/holochain-client.tsThis 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
src/client-provider.tsThis 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
src/hrea-test.tsThis component consumes the context provided by <client-provider> and uses the Apollo Client to send queries and mutations to hREA.
index.html
index.htmlFinally, your ui/index.html ties everything together.
4. How It Works
index.htmlloads the<client-provider>component.client-provider.tsis rendered. ItsfirstUpdatedlifecycle method triggers theconnect()method in ourHolochainConnectionclass.While connecting, it displays a "Connecting..." status message.
Once the connection is successful,
HolochainConnectioncreates the Apollo Client for hREA and calls the status update callback.The
ClientProviderreceives the 'connected' status and sets thehreaClientContextvalue, passing down the client instances. It then renders its<slot>, which contains the<hrea-test>component.hrea-test.tsconsumes the context. Now that it has a value, it renders the UI with the buttons.When you click a button, a method like
createPersonis called, which uses thethis.hreaClientinstance to send a GraphQL mutation.The results are added to the component's reactive
resultsstate, causing the UI to re-render and display the outcome.
Last updated