Building a UI for Subgraph Queries on Somnia
This guide will teach you how to create a minimal, functional UI that queries blockchain data from a Somnia subgraph using Next.js, Apollo Client, and GraphQL.
Prerequisites
Basic knowledge of React and Next.js
Node.js installed (v16 or higher)
A deployed subgraph on Somnia (we'll use SomFlip as an example)
What You'll Build
A clean, minimal interface that:
Displays all coin flip results with pagination
Shows a live feed that auto-refreshes every 5 seconds
Create a Next.js Project
Start by creating a new Next.js application with TypeScript and TailwindCSS:
npx create-next-app@latest somnia-subgraph-ui --typescript --tailwind --app
cd somnia-subgraph-ui
Install the required GraphQL dependencies:
npm install @apollo/client graphql
Understand the Architecture
Before we code, let's understand how the pieces fit together:
User Interface (React Components)
↓
Apollo Client (GraphQL Client)
↓
GraphQL Queries
↓
Somnia Subgraph API
↓
Blockchain Data
Set Up Apollo Client
Apollo Client is a comprehensive GraphQL client that manages data fetching, caching, and state management. Create a lib
directory and create a file apollo-client.ts
import { ApolloClient, InMemoryCache } from '@apollo/client';
const client = new ApolloClient({
// The URI of your subgraph endpoint
uri: 'https://proxy.somnia.chain.love/subgraphs/name/somnia-testnet/SomFlip',
// Apollo's caching layer - stores query results
cache: new InMemoryCache(),
});
export default client;
The URI
is the endpoint where your subgraph is hosted, and InMemoryCache
will store the query results in memory for fast access
Create the Apollo Provider Wrapper
React components need access to the Apollo Client. We'll create a wrapper component that provides this access to the entire app. Create a components
directory and create a file ApolloWrapper.tsx
.
'use client'; // Next.js 13+ directive for client-side components
import { ApolloProvider } from '@apollo/client';
import client from '@/lib/apollo-client';
// This component wraps your app with Apollo's context provider
export default function ApolloWrapper({
children
}: {
children: React.ReactNode
}) {
return (
<ApolloProvider client={client}>
{children}
</ApolloProvider>
);
}
ApolloProvider: Makes the Apollo Client available to all child components
Update app/layout.tsx
import ApolloWrapper from '@/components/ApolloWrapper';
export default function RootLayout({
children,
}: {
children: React.ReactNode;
}) {
return (
<html lang="en">
<body>
<ApolloWrapper>
{children}
</ApolloWrapper>
</body>
</html>
);
}
Create GraphQL Queries
GraphQL queries define exactly what data you want from the subgraph. Let's create queries for our two main features. In the lib
directory create a queries.ts
file.
Note the following:
gql
is the template literal tag that parses GraphQL queriesVariables start with $ and have types (Int!, String!, etc.)
! means the field is required (non-nullable)
Build the All Flips Component
Let's build the All Flips component step by step, understanding each part in detail.
Set Up the Component File
In the components
directory create AllFlips.tsx
file and add the following imports.
'use client';
import { useState } from 'react';
import { useQuery } from '@apollo/client';
import { GET_FLIP_RESULTS } from '@/lib/queries';
Create Utility Functions
Add these helper functions at the top of your component:
/ Shortens long blockchain addresses for display
// Example: "0x1234567890abcdef" becomes "0x1234...cdef"
const truncateHash = (hash: string) => {
return `${hash.slice(0, 6)}...${hash.slice(-4)}`;
};
// Converts wei (smallest unit) to ether (display unit)
// 1 ether = 1,000,000,000,000,000,000 wei (10^18)
const formatEther = (wei: string) => {
const ether = parseFloat(wei) / 1e18;
return ether.toFixed(4); // Show 4 decimal places
};
// Converts Unix timestamp to readable date
// Blockchain stores time as seconds since Jan 1, 1970
const formatTime = (timestamp: string) => {
const milliseconds = parseInt(timestamp) * 1000;
const date = new Date(milliseconds);
return date.toLocaleString();
};
Component Function and State Management
export default function AllFlips() {
// Track which page of results we're viewing
const [page, setPage] = useState(0);
const itemsPerPage = 30;
the number ofpage
tracks the current page number (starting at 0), which is used to calculate the number of results to skip. It updates when the user clicks the Previous/Next button.
Execute the GraphQL Query
const { loading, error, data } = useQuery(GET_FLIP_RESULTS, {
variables: {
first: itemsPerPage, // How many results to fetch
skip: page * itemsPerPage, // How many to skip
orderBy: 'blockTimestamp', // Sort by time
orderDirection: 'desc', // Newest first
},
});
The useQuery
function is set to loading: true
while fetching data
and the data
contains the query results when successful.
Handle Query States
// Show loading spinner while fetching
if (loading) {
return <div className="text-center py-8 text-gray-500">Loading...</div>;
}
// Show error message if query failed
if (error) {
return (
<div className="text-center py-8 text-red-500">
Error: {error.message}
</div>
);
}
// Check if we have results
if (!data?.flipResults?.length) {
return <div className="text-center py-8 text-gray-500">No flips found</div>;
}
This prevents rendering errors and andles edge cases gracefully
Render the Table View
Build the Live Feed Component
Now let's build the Live Feed component that automatically refreshes to show new flips.
Set Up the Component
In the components
directory create a LiveFeed.tsx
file and update the imports.
'use client';
import { useQuery } from '@apollo/client';
import { GET_RECENT_FLIPS } from '@/lib/queries';
Create Utility Functions
const truncateHash = (hash: string) => {
return `${hash.slice(0, 6)}...${hash.slice(-4)}`;
};
const formatEther = (wei: string) => {
return (parseFloat(wei) / 1e18).toFixed(4);
};
Component Function with Auto-Refresh
export default function LiveFeed() {
// Execute query with automatic polling
const { loading, error, data } = useQuery(GET_RECENT_FLIPS, {
variables: {
first: 10 // Get 10 most recent flips
},
pollInterval: 5000, // Refresh every 5 seconds (5000ms)
});
The pollInterval
automatically re-executes the query every 5 seconds. New flips appear without user interaction with Apollo Client handling the refresh logic. You can set to 0 or remove to disable auto-refresh
Handle Query States
// Same loading/error handling as AllFlips
if (loading) {
return <div className="text-center py-8 text-gray-500">Loading...</div>;
}
if (error) {
return <div className="text-center py-8 text-red-500">Error: {error.message}</div>;
}
if (!data?.flipResults?.length) {
return <div className="text-center py-8 text-gray-500">No recent flips</div>;
}
Complete Live Feed Component
The key differences from the AllFlips page are that there is no pagination (shows most recent only), and it auto-refreshes with pollInterval, with a visual emphasis on win/loss status.
Update the Main Page.tsx
Run Your Application
npm run dev
Visit http://localhost:3000
to see your UI in action.
Last updated