### Local Development Setup
Source: https://github.com/accesslayerorg/accesslayer-client/blob/dev/README.md
Commands to install dependencies and start the development server.
```bash
pnpm install
pnpm dev
```
--------------------------------
### Install Dependencies
Source: https://github.com/accesslayerorg/accesslayer-client/blob/dev/CONTRIBUTING.md
Install the project dependencies using pnpm.
```bash
pnpm install
```
--------------------------------
### Initialize Environment Variables
Source: https://github.com/accesslayerorg/accesslayer-client/blob/dev/CONTRIBUTING.md
Copy the example environment file to create your local configuration.
```bash
cp .env.example .env
```
--------------------------------
### Directory layout for utility tests
Source: https://github.com/accesslayerorg/accesslayer-client/blob/dev/docs/utils-testing-guide.md
Example showing the side-by-side placement of a utility file and its corresponding test file.
```text
src/utils/
├─ formatNumber.utils.ts
└─ formatNumber.utils.test.ts ← test file
```
--------------------------------
### DisabledReason string examples
Source: https://github.com/accesslayerorg/accesslayer-client/blob/dev/docs/BuyActionHelperText-DisabledReason.md
Examples of string values that can be passed to the disabledReason prop to display specific feedback to the user.
```tsx
// Insufficient balance
disabledReason = 'Insufficient balance to complete this purchase';
// Network issue
disabledReason = 'Network connection required to proceed';
// Wallet not connected
disabledReason = 'Connect your wallet to enable purchases';
// Creator unavailable
disabledReason = 'This creator is currently unavailable';
// Maximum keys reached
disabledReason = 'Maximum number of keys already purchased';
```
--------------------------------
### BuyActionExample implementation
Source: https://github.com/accesslayerorg/accesslayer-client/blob/dev/docs/BuyActionHelperText-DisabledReason.md
A complete example showing how to determine a disabled reason based on wallet connection, balance, network availability, and purchase limits, and passing it to the BuyActionHelperText component.
```tsx
import { useState } from 'react';
import { useAccount } from 'wagmi';
import BuyActionHelperText from '@/components/common/BuyActionHelperText';
import { Button } from '@/components/ui/button';
export function BuyActionExample() {
const { isConnected } = useAccount();
const [transactionState, setTransactionState] = useState<
'idle' | 'submitting' | 'failed' | 'success'
>('idle');
// Example conditions that might disable an action
const userBalance = 0.5; // ETH
const requiredAmount = 1.0; // ETH
const isNetworkAvailable = true;
const hasReachedLimit = false;
// Determine disabled reason based on conditions
const getDisabledReason = () => {
if (!isConnected) {
return 'Connect your wallet to enable purchases';
}
if (userBalance < requiredAmount) {
return `Insufficient balance. You need ${requiredAmount - userBalance} ETH more`;
}
if (!isNetworkAvailable) {
return 'Network connection required to proceed';
}
if (hasReachedLimit) {
return 'Maximum number of keys already purchased';
}
return undefined; // No disabled reason
};
const disabledReason = getDisabledReason();
const isDisabled = !!disabledReason || transactionState === 'submitting';
return (
);
}
```
--------------------------------
### Test file structure example
Source: https://github.com/accesslayerorg/accesslayer-client/blob/dev/docs/testing-conventions.md
Visual representation of the directory structure where tests are co-located in __tests__ folders next to the source code.
```text
src/hooks/
├─ useFormatXlm.ts
└─ __tests__/
└─ useFormatXlm.test.ts
src/pages/
├─ LandingPage.tsx
└─ __tests__/
├─ LandingPage.holdings.test.tsx ← unit-ish page test
└─ LandingPage.sellFlow.integration.test.tsx ← integration test
```
--------------------------------
### Off-chain mutation toast handling
Source: https://github.com/accesslayerorg/accesslayer-client/blob/dev/docs/error-handling-conventions.md
Example of handling errors for simple off-chain writes like clipboard operations using a try-catch block.
```ts
// Excerpt from CreatorProfileHeader
const handleShare = async () => {
try {
await navigator.clipboard.writeText(profileUrl);
showToast.success('Profile link copied to clipboard!');
} catch {
showToast.error('Could not copy the profile link. Please try again.');
}
};
```
--------------------------------
### Minimal page component structure
Source: https://github.com/accesslayerorg/accesslayer-client/blob/dev/docs/adding-page-routes.md
Example of a standard page component in src/pages/AboutPage.tsx, demonstrating the required default export and semantic HTML structure.
```tsx
// src/pages/AboutPage.tsx
export default function AboutPage() {
return (
About Access Layer
Access Layer is a Stellar-native creator keys marketplace.
);
}
```
--------------------------------
### Ephemeral UI State Examples
Source: https://github.com/accesslayerorg/accesslayer-client/blob/dev/docs/state-management.md
Use React useState for local UI concerns that do not require server synchronization.
```typescript
const [open, setOpen] = useState(false)
const [query, setQuery] = useState('')
const [activeTab, setActiveTab] = useState('overview')
const [submitting, setSubmitting] = useState(false)
```
--------------------------------
### Create a shared counter hook
Source: https://github.com/accesslayerorg/accesslayer-client/blob/dev/docs/shared-hooks.md
A minimal example of a reusable hook in src/hooks/useCounter.ts that manages count state and an increment function.
```ts
// src/hooks/useCounter.ts
import { useCallback, useState } from 'react';
export const useCounter = (initialValue = 0) => {
const [count, setCount] = useState(initialValue);
const increment = useCallback(() => setCount(value => value + 1), []);
return { count, increment };
};
```
--------------------------------
### Integrating BuyActionHelperText with CreatorCard
Source: https://github.com/accesslayerorg/accesslayer-client/blob/dev/docs/BuyActionHelperText-DisabledReason.md
An example of using BuyActionHelperText within a functional component to conditionally display a disabled reason based on transaction state or balance checks.
```tsx
const CreatorCard: React.FC = ({ creator, className }) => {
const { isConnected } = useAccount();
const [transactionState, setTransactionState] = useState<
'idle' | 'submitting' | 'failed' | 'success'
>('idle');
// Example: Check if user has sufficient balance
const hasInsufficientBalance = true; // Replace with actual balance check
const disabledReason = hasInsufficientBalance
? 'Insufficient balance to complete this purchase'
: undefined;
return (
{/* ... other card content ... */}
);
};
```
--------------------------------
### Verify Implementation Commands
Source: https://github.com/accesslayerorg/accesslayer-client/blob/dev/docs/adding-page-and-data-fetching.md
Commands to run the development server, lint the code, and build the project for verification.
```bash
pnpm dev # visit http://localhost:5173/creators
pnpm lint
pnpm build
```
--------------------------------
### Verify local build
Source: https://github.com/accesslayerorg/accesslayer-client/blob/dev/docs/adding-page-routes.md
Run these commands to verify the new page locally.
```bash
pnpm dev # visit http://localhost:5173/about
pnpm lint
pnpm build
```
--------------------------------
### NetworkBadge in a Transaction Surface
Source: https://github.com/accesslayerorg/accesslayer-client/blob/dev/docs/NetworkBadge.md
Example of placing the NetworkBadge within a transaction card component to indicate the network context of the transaction.
```tsx
import { NetworkBadge } from '@/components/common/NetworkBadge';
function TransactionCard({ transaction }) {
return (
Transaction Details
{/* Transaction details */}
);
}
```
--------------------------------
### Declare variable in .env.example
Source: https://github.com/accesslayerorg/accesslayer-client/blob/dev/docs/environment-variables.md
Add new variables to .env.example with a comment explaining their purpose and default value.
```env
# Feature flag for the creator discovery experiment. Use `true` to enable locally.
VITE_ENABLE_CREATOR_DISCOVERY=false
```
--------------------------------
### Run local development server
Source: https://github.com/accesslayerorg/accesslayer-client/blob/dev/docs/marketing-page-copy.md
Optional command to run the application locally for previewing changes if a local environment is already set up.
```bash
pnpm dev
```
--------------------------------
### Project Verification
Source: https://github.com/accesslayerorg/accesslayer-client/blob/dev/README.md
Commands to run linting and build the project for verification.
```bash
pnpm lint
pnpm build
```
--------------------------------
### Casting and inspecting ApiError
Source: https://github.com/accesslayerorg/accesslayer-client/blob/dev/docs/error-handling-in-hooks.md
Example of casting a generic error to ApiError within an onError callback to access status codes, messages, and field-level validation details.
```ts
import { ApiError } from '@/services/api.service';
onError: error => {
const apiError = error as ApiError;
console.log(apiError.status); // 0, 400, 403, 422, 500 …
console.log(apiError.message); // human-readable message from the API
console.log(apiError.response?.errors); // field-level details on 422
};
```
--------------------------------
### Create React Query hook in src/hooks/useWalletHoldings.ts
Source: https://github.com/accesslayerorg/accesslayer-client/blob/dev/docs/api-layer.md
Implement a custom hook using the service method and query key, leveraging the existing QueryClientProvider.
```ts
// src/hooks/useWalletHoldings.ts
import { useQuery } from '@tanstack/react-query';
import { walletService } from '@/services/wallet.service';
import { queryKeys } from '@/lib/queryKeys';
export function useWalletHoldings(address: string | undefined) {
return useQuery({
queryKey: queryKeys.wallet.holdings(address ?? ''),
queryFn: () => walletService.getHoldings(address!),
enabled: Boolean(address),
});
}
```
--------------------------------
### Run coverage report with pnpm
Source: https://github.com/accesslayerorg/accesslayer-client/blob/dev/docs/utils-testing-guide.md
Command to generate a test coverage report to verify branch coverage for utility helpers.
```bash
pnpm test --coverage
```
--------------------------------
### Add useCreatorList.ts Hook
Source: https://github.com/accesslayerorg/accesslayer-client/blob/dev/docs/adding-page-and-data-fetching.md
Implements the React Query hook to fetch creator data using the course service.
```ts
// src/hooks/useCreatorList.ts
import { useQuery } from '@tanstack/react-query';
import { queryKeys } from '@/lib/queryKeys';
import { courseService } from '@/services/course.service';
export function useCreatorList() {
return useQuery({
queryKey: queryKeys.creators.list(),
queryFn: () => courseService.getCourses(),
});
}
```
--------------------------------
### Mounting NetworkMismatchBanner
Source: https://github.com/accesslayerorg/accesslayer-client/blob/dev/docs/error-handling-conventions.md
The NetworkMismatchBanner component should be mounted in layouts where users can initiate trades. It returns null when the wallet is on the correct network.
```tsx
// Wherever the user can trade
```
--------------------------------
### Asynchronous State Implementation Blueprint
Source: https://github.com/accesslayerorg/accesslayer-client/blob/dev/docs/state-management.md
A complete pattern for handling loading, error, and data states, including a manual refetch trigger for error recovery.
```tsx
import React from 'react';
import { useCreatorDetail } from '@/hooks/useCreatorDetail';
import { CreatorSkeleton } from '@/components/common/CreatorSkeleton';
interface CreatorDashboardPageProps {
creatorId: string;
}
export function CreatorDashboardPage({ creatorId }: CreatorDashboardPageProps) {
const {
data: creator,
isLoading,
isError,
error,
refetch,
} = useCreatorDetail(creatorId);
if (isLoading) {
return ;
}
if (isError) {
return (
);
}
```
--------------------------------
### Run unit tests for ProfileTabPillGroup
Source: https://github.com/accesslayerorg/accesslayer-client/blob/dev/docs/CreatorProfileAnchorLinks.md
Commands to execute the unit tests for the ProfileTabPillGroup component or the entire test suite.
```bash
# Run the new unit tests
pnpm test ProfileTabPillGroup
# Run the full test suite
pnpm test
```
--------------------------------
### Implement useCreatorKeys and useBuyCreatorKey hooks
Source: https://github.com/accesslayerorg/accesslayer-client/blob/dev/docs/error-handling-in-hooks.md
This hook implementation uses React Query to manage read and write operations, with a centralized onError handler to process different API error statuses.
```ts
// src/hooks/useCreatorKeys.ts
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { ApiError } from '@/services/api.service';
import showToast from '@/utils/toast.util';
import { creatorKeysService } from '@/services/creatorKeys.service';
// --- Read ---
export function useCreatorKeys(creatorId: string) {
return useQuery({
queryKey: ['creator-keys', creatorId],
queryFn: () => creatorKeysService.getKeys(creatorId),
staleTime: 30_000,
});
}
// --- Write ---
export function useBuyCreatorKey() {
const queryClient = useQueryClient();
return useMutation({
mutationFn: ({
creatorId,
amount,
}: {
creatorId: string;
amount: number;
}) => creatorKeysService.buyKey(creatorId, amount),
onError: error => {
const apiError = error as ApiError;
// No response received — user is likely offline
if (apiError.status === 0) {
showToast.error(
'Network error. Check your connection and try again.'
);
return;
}
// Server-side failure — not actionable by the user
if (apiError.status >= 500) {
showToast.error(
'The server ran into a problem. Please try again shortly.'
);
return;
}
// 422 Validation — show the first field error if available
if (apiError.status === 422 && apiError.response?.errors?.length) {
showToast.error(apiError.response.errors[0].message);
return;
}
// All other 4xx — the API message is safe to surface
showToast.error(apiError.message);
},
onSuccess: (_, { creatorId }) => {
// Invalidate relevant queries so the UI reflects the purchase
queryClient.invalidateQueries({
queryKey: ['creator-keys', creatorId],
});
queryClient.invalidateQueries({ queryKey: ['user-holdings'] });
showToast.success('Key purchased successfully!');
},
});
}
```
--------------------------------
### useQuery Hook Implementation
Source: https://github.com/accesslayerorg/accesslayer-client/blob/dev/docs/error-handling-in-hooks.md
Defines a thin hook for fetching creator profiles using useQuery.
```ts
// src/hooks/useCreatorProfile.ts
import { useQuery } from '@tanstack/react-query';
import { creatorService } from '@/services/creator.service';
export function useCreatorProfile(creatorId: string) {
return useQuery({
queryKey: ['creator-profile', creatorId],
queryFn: () => creatorService.getProfile(creatorId),
staleTime: 30_000,
});
}
```
--------------------------------
### Basic Usage of BuyActionHelperText
Source: https://github.com/accesslayerorg/accesslayer-client/blob/dev/docs/BuyActionHelperText-DisabledReason.md
A simple implementation of the BuyActionHelperText component showing how to pass the disabledReason prop.
```tsx
import BuyActionHelperText from '@/components/common/BuyActionHelperText';
;
```
--------------------------------
### Basic NetworkBadge Usage
Source: https://github.com/accesslayerorg/accesslayer-client/blob/dev/docs/NetworkBadge.md
Demonstrates basic implementation of the NetworkBadge component, including network selection, indicator toggling, and custom class application.
```tsx
import { NetworkBadge } from '@/components/common/NetworkBadge';
// Basic usage - testnet (default)
// Mainnet
// Without indicator dot
// With custom className
```
--------------------------------
### Create AboutPage component
Source: https://github.com/accesslayerorg/accesslayer-client/blob/dev/docs/adding-page-routes.md
Create a new page component file at src/pages/AboutPage.tsx.
```tsx
// src/pages/AboutPage.tsx
import { Link } from 'react-router';
import { Button } from '@/components/ui/button';
export default function AboutPage() {
return (
About Access Layer
Access Layer is a Stellar-native creator keys marketplace built on
the open AccessLayer protocol.
);
}
```
--------------------------------
### Extend Query Key Factory for New Entities
Source: https://github.com/accesslayerorg/accesslayer-client/blob/dev/docs/react-query-cache-conventions.md
Demonstrates adding a new entity group to the central factory following the established pattern.
```typescript
import type { GetCoursesParams } from '@/services/course.service';
export const queryKeys = {
creators: { /* … */ },
wallet: { /* … */ },
courses: {
all: ['courses'] as const,
list: (params?: GetCoursesParams) =>
['courses', 'list', params ?? null] as const,
detail: (id: string) => ['courses', 'detail', id] as const,
enrollments: (courseId: string) =>
['courses', courseId, 'enrollments'] as const,
},
};
```
--------------------------------
### Define service method in src/services/wallet.service.ts
Source: https://github.com/accesslayerorg/accesslayer-client/blob/dev/docs/api-layer.md
Create a service method that calls the API, extracts the data, and handles errors using the base service class.
```ts
// src/services/wallet.service.ts
import { BaseApiService, type APIResponse } from './api.service';
export interface Holding {
creatorId: string;
quantity: number;
priceStroops: number;
}
class WalletService extends BaseApiService {
async getHoldings(address: string): Promise {
try {
const response = await this.api.get>(
`/wallets/${address}/holdings`
);
return response.data.data;
} catch (error) {
throw this.handleError(error);
}
}
}
export const walletService = new WalletService();
```
--------------------------------
### Run only utils tests with pnpm
Source: https://github.com/accesslayerorg/accesslayer-client/blob/dev/docs/utils-testing-guide.md
Command to execute tests specifically for files located in the src/utils directory using Vitest.
```bash
pnpm test "src/utils/**/*.test.ts"
```
--------------------------------
### Run local validation tests
Source: https://github.com/accesslayerorg/accesslayer-client/blob/dev/docs/ClaimActionHelperText-DisabledReason.md
Execute the test suite for the claim action disabled reason utility using pnpm.
```bash
pnpm test src/utils/__tests__/claimActionDisabledReason.test.ts
```
--------------------------------
### Validate variables in src/utils/env.utils.ts
Source: https://github.com/accesslayerorg/accesslayer-client/blob/dev/docs/environment-variables.md
Define the schema using Zod and parse the environment variables at startup to ensure type safety and catch configuration errors early.
```ts
const envSchema = z.object({
VITE_ENABLE_CREATOR_DISCOVERY: z.coerce.boolean().default(false),
});
export const env = envSchema.parse({
VITE_ENABLE_CREATOR_DISCOVERY: import.meta.env.VITE_ENABLE_CREATOR_DISCOVERY,
});
```
--------------------------------
### Register Query Key for Wallet Holdings
Source: https://github.com/accesslayerorg/accesslayer-client/blob/dev/docs/api-layer.md
Add the holdings query key to the existing queryKeys configuration file.
```ts
// src/lib/queryKeys.ts (existing file — add the entry)
wallet: {
holdings: (address: string) => ['wallet', address, 'holdings'] as const,
},
```
--------------------------------
### Mocking useWallet hooks
Source: https://github.com/accesslayerorg/accesslayer-client/blob/dev/docs/testing-conventions.md
Use this pattern to mock wallet state hooks in component tests. It provides mock implementations for useWalletHoldings and useTradeMutation.
```tsx
vi.mock('@/hooks/useWallet', () => ({
// "connected wallet holding 2 keys of creator-a"
useWalletHoldings: () => ({
data: [{ creatorId: 'creator-a', quantity: 2, priceStroops: 500_000, price: 0.05, pending: false }],
}),
useTradeMutation: () => ({ mutateAsync: vi.fn(), isPending: false }),
}));
```
--------------------------------
### Show Toast for User-Initiated Actions
Source: https://github.com/accesslayerorg/accesslayer-client/blob/dev/docs/error-handling-in-hooks.md
Use a toast for errors resulting from mutations where the page remains functional and the fix involves retrying or changing input.
```ts
onError: error => {
const apiError = error as ApiError;
showToast.error(
apiError.status >= 500
? 'Something went wrong. Try again.'
: apiError.message
);
};
```
--------------------------------
### Consume hooks in CreatorKeysSection component
Source: https://github.com/accesslayerorg/accesslayer-client/blob/dev/docs/error-handling-in-hooks.md
This component demonstrates how to use the hooks and handle loading and error states in the UI.
```tsx
import { ApiError } from '@/services/api.service';
import { useCreatorKeys, useBuyCreatorKey } from '@/hooks/useCreatorKeys';
import SectionErrorBoundary from '@/components/common/SectionErrorBoundary';
function CreatorKeysSection({ creatorId }: { creatorId: string }) {
const { data: keys, isLoading, isError, error } = useCreatorKeys(creatorId);
const { mutate: buyKey, isPending } = useBuyCreatorKey();
if (isLoading) return ;
if (isError) {
const apiError = error as ApiError;
return (
{apiError.status >= 500
? 'Unable to load keys right now. Please try again later.'
: apiError.message}
);
}
return (
// SectionErrorBoundary catches any render-time throws inside KeysList
buyKey({ creatorId, amount })}
isBuying={isPending}
/>
);
}
```
--------------------------------
### Right: Using React Query data directly
Source: https://github.com/accesslayerorg/accesslayer-client/blob/dev/docs/state-management.md
Access server data directly from the hook to ensure the UI remains in sync with the cache.
```tsx
function CreatorProfile({ id }: { id: string }) {
const { data: creator } = useCreatorDetail(id);
return
{creator?.title}
;
}
```
--------------------------------
### Handle Loading and Error States
Source: https://github.com/accesslayerorg/accesslayer-client/blob/dev/docs/adding-page-and-data-fetching.md
Implement explicit handling for loading, error, and missing data states in your components.
```tsx
import { CreatorProfileHeaderSkeleton } from '@/components/common/CreatorSkeleton';
import { ApiError } from '@/services/api.service';
export default function YourDetailPage() {
const { id } = useParams<{ id: string }>();
const { data, isLoading, error } = useYourData(id || '');
// 1. LOADING: Show a skeleton while fetching
if (isLoading) {
return (
);
}
// 2. ERROR: Throw to error boundary or render error UI
if (error) {
throw error; // handled by error boundary (see Part 5)
}
// 3. NO DATA: Throw a 404 error
if (!data) {
throw new ApiError('Not found', 404);
}
// 4. SUCCESS: Render your page
return (
{data.title}
{/* render data */}
);
}
```
--------------------------------
### Unit test for formatNumber helper
Source: https://github.com/accesslayerorg/accesslayer-client/blob/dev/docs/utils-testing-guide.md
A Vitest test suite for the formatNumber pure function, covering integer, floating-point, and negative number cases.
```ts
// src/utils/formatNumber.utils.test.ts
import { describe, expect, it } from 'vitest';
import { formatNumber } from './formatNumber.utils';
describe('formatNumber utils', () => {
it('formats an integer with commas', () => {
expect(formatNumber(1234567)).toBe('1,234,567.00');
});
it('formats a floating‑point number with two decimals', () => {
expect(formatNumber(1234.5)).toBe('1,234.50');
});
it('handles negative numbers', () => {
expect(formatNumber(-9876.543)).toBe('-9,876.54');
});
});
```
--------------------------------
### Buy flow mutation failure (Mode 1 + Mode 5)
Source: https://github.com/accesslayerorg/accesslayer-client/blob/dev/docs/error-handling-conventions.md
Handles mutation errors by displaying a toast notification for immediate feedback and setting a persistent failure state for support details.
```tsx
// src/components/common/CreatorCard.tsx (excerpt)
const buy = useBuyCreatorKey();
const handleBuy = async (amount: number) => {
try {
await buy.mutateAsync({ creatorId, amount });
} catch (err) {
const apiError = err as ApiError;
// Mode 1: quick prompt
showToast.error(
apiError.status === 0
? 'Network error. Check your connection.'
: apiError.message
);
// Mode 5: persistent banner + drawer for support detail
setFailure({
errorMessage: apiError.message,
errorCode: apiError.response?.code,
timestamp: Date.now(),
});
}
};
```
--------------------------------
### API Service Folder Structure
Source: https://github.com/accesslayerorg/accesslayer-client/blob/dev/docs/api-layer.md
The directory layout for API services located in src/services/.
```text
src/services/
├── api.service.ts # Base class — all services extend this
├── auth.service.ts # Authentication endpoints
└── course.service.ts # Creator / course data endpoints
```
--------------------------------
### Define a Service Layer Class
Source: https://github.com/accesslayerorg/accesslayer-client/blob/dev/docs/adding-page-and-data-fetching.md
Create a service class in src/services/ that extends BaseApiService to handle domain-specific data fetching.
```ts
// src/services/your.service.ts
import { BaseApiService, type APIResponse } from './api.service';
export interface YourEntity {
id: string;
title: string;
description: string;
// ... other fields
}
class YourService extends BaseApiService {
async getYourData(id: string): Promise {
try {
const response = await this.api.get>(
`/your-endpoint/${id}`
);
return response.data.data;
} catch (error) {
throw this.handleError(error);
}
}
}
export const yourService = new YourService();
```
--------------------------------
### Create a Custom Data Fetching Hook
Source: https://github.com/accesslayerorg/accesslayer-client/blob/dev/docs/adding-page-and-data-fetching.md
Create a custom hook in src/hooks/ that wraps the React Query call to avoid direct fetching in components.
```ts
// src/hooks/useYourData.ts
import { useQuery } from '@tanstack/react-query';
import { queryKeys } from '@/lib/queryKeys';
import { yourService } from '@/services/your.service';
export function useYourData(id: string) {
return useQuery({
queryKey: queryKeys.yourEntity.detail(id), // see Query Key Factory below
queryFn: () => yourService.fetchData(id),
enabled: !!id, // don't fetch until `id` is defined
});
}
```
--------------------------------
### Link to new route
Source: https://github.com/accesslayerorg/accesslayer-client/blob/dev/docs/adding-page-routes.md
Import Link and add a navigation link to the new route within an existing component.
```tsx
import { Link } from 'react-router';
// inside the JSX you return
About this project
;
```
--------------------------------
### Create a Page Component in src/pages/CreatorDetailPage.tsx
Source: https://github.com/accesslayerorg/accesslayer-client/blob/dev/docs/adding-page-and-data-fetching.md
A standard page component implementation using a default export and a main semantic landmark for layout.
```tsx
// src/pages/CreatorDetailPage.tsx
export default function CreatorDetailPage() {
// No props here ↑
return (
Page Title
);
}
```
--------------------------------
### NetworkBadge in a Header
Source: https://github.com/accesslayerorg/accesslayer-client/blob/dev/docs/NetworkBadge.md
Shows how to integrate the NetworkBadge into an application header using an environment variable to determine the active network.
```tsx
import { NetworkBadge } from '@/components/common/NetworkBadge';
function AppHeader() {
const currentNetwork = import.meta.env.VITE_STELLAR_NETWORK || 'testnet';
return (
My Stellar App
);
}
```
--------------------------------
### Wire protection in App.tsx
Source: https://github.com/accesslayerorg/accesslayer-client/blob/dev/docs/adding-page-routes.md
Apply the RequireAuth wrapper to specific routes within the createBrowserRouter configuration.
```tsx
// src/App.tsx
import RequireAuth from './components/auth/RequireAuth';
import DashboardPage from './pages/DashboardPage';
const router = createBrowserRouter([
{ path: '/', element: },
{
path: '/dashboard',
// Public route → element:
// Protected route → wrap in :
element: (
),
},
{ path: '*', element: },
]);
```
--------------------------------
### BuyActionHelperText Component API
Source: https://github.com/accesslayerorg/accesslayer-client/blob/dev/docs/BuyActionHelperText-DisabledReason.md
The BuyActionHelperText component accepts props to manage the transaction state and display optional disabled reason messages.
```APIDOC
## BuyActionHelperText Component
### Description
A React component used to display the current transaction state and an optional message explaining why an action might be disabled.
### Props
- **state** ('idle' | 'submitting' | 'failed' | 'success') - Required - Current transaction state.
- **className** (string) - Optional - Additional CSS classes to apply to the component.
- **disabledReason** (string) - Optional - The message to display when the action is disabled.
### Usage Example
```tsx
```
```
--------------------------------
### Usage of getClaimActionDisabledReasonText
Source: https://github.com/accesslayerorg/accesslayer-client/blob/dev/docs/ClaimActionHelperText-DisabledReason.md
Import and use the utility to retrieve standardized disabled reason text based on a specific reason key.
```ts
import { getClaimActionDisabledReasonText } from '@/utils/claimActionDisabledReason';
const disabledReason = getClaimActionDisabledReasonText('wallet_not_connected');
// "Claim is unavailable because your wallet is not connected. Connect your wallet to continue."
```
--------------------------------
### Avoid direct access to import.meta.env
Source: https://github.com/accesslayerorg/accesslayer-client/blob/dev/docs/environment-variables.md
Directly accessing environment variables in components is an anti-pattern that bypasses validation. Use the centralized env object instead.
```tsx
// Avoid this.
const backendUrl = import.meta.env.VITE_BACKEND_URL;
```
```tsx
import { env } from '@/utils/env.utils';
const backendUrl = env.VITE_BACKEND_URL;
```
--------------------------------
### Mocking the service with React Query
Source: https://github.com/accesslayerorg/accesslayer-client/blob/dev/docs/testing-conventions.md
Preferred pattern for integration tests where the service is mocked but React Query remains active to test caching and invalidation. Always create a fresh QueryClient per render and disable retries.
```tsx
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { courseService } from '@/services/course.service';
vi.mock('@/services/course.service', () => ({
courseService: { getCourses: vi.fn() },
}));
const mockGetCourses = vi.mocked(courseService.getCourses);
const renderPage = () =>
render(
);
// in the test:
mockGetCourses.mockResolvedValue([…fixtures…]);
```
--------------------------------
### Handle Server Errors (status >= 500)
Source: https://github.com/accesslayerorg/accesslayer-client/blob/dev/docs/error-handling-in-hooks.md
Use this check for 5xx errors where the API failed. Avoid showing raw server messages and provide a generic fallback instead.
```ts
if (apiError.status >= 500) {
showToast.error('The server ran into a problem. Please try again shortly.');
return;
}
```
--------------------------------
### Refetch manually with useQuery
Source: https://github.com/accesslayerorg/accesslayer-client/blob/dev/docs/state-management.md
Forces an immediate reload of data, typically triggered by a user action like a refresh button. Avoid using this inside effects or after mutations to prevent race conditions with cache invalidation.
```ts
const { refetch } = useQuery({ queryKey: queryKeys.wallet.holdings(address), ... });
```
--------------------------------
### Update Query Key Factory
Source: https://github.com/accesslayerorg/accesslayer-client/blob/dev/docs/adding-page-and-data-fetching.md
Add new entities to the existing query key factory file.
```ts
// src/lib/queryKeys.ts (existing)
import type { GetYourParams } from '@/services/your.service';
export const queryKeys = {
creators: {
/* ... */
},
wallet: {
/* ... */
},
yourEntity: {
all: ['yourEntity'] as const,
list: (params?: GetYourParams) =>
['yourEntity', 'list', params ?? null] as const,
detail: (id: string) => ['yourEntity', 'detail', id] as const,
},
};
```
--------------------------------
### Create RequireAuth wrapper component
Source: https://github.com/accesslayerorg/accesslayer-client/blob/dev/docs/adding-page-routes.md
A React component that checks authentication state using wagmi's useAccount and redirects unauthenticated users or displays a loading placeholder.
```tsx
// src/components/auth/RequireAuth.tsx
import type { ReactNode } from 'react';
import { useAccount } from 'wagmi';
import { Navigate, useLocation } from 'react-router';
import PendingOnboardingPlaceholder from '@/components/common/PendingOnboardingPlaceholder';
interface RequireAuthProps {
children: ReactNode;
}
export default function RequireAuth({ children }: RequireAuthProps) {
const { isConnected, isConnecting } = useAccount();
const location = useLocation();
// Show the placeholder while a fresh wallet connection is in flight
// so the user isn't redirected to "/" mid-connect. Once it resolves,
// isConnected flips to true and we render the protected page below.
// Note: isReconnecting is intentionally NOT in this branch — a
// reconnect of a prior session keeps the user authenticated, so
// rendering the protected page during a reconnect is fine.
if (isConnecting) {
return ;
}
if (!isConnected) {
// Send unauthenticated users back to the homepage while preserving
// the path they tried to reach so a future flow can deep-link them
// back here after they connect.
return ;
}
return <>{children}>;
}
```
--------------------------------
### Handling empty disabledReason states
Source: https://github.com/accesslayerorg/accesslayer-client/blob/dev/docs/BuyActionHelperText-DisabledReason.md
Demonstrates how the component renders nothing when the disabledReason prop is undefined, null, empty, or contains only whitespace.
```tsx
// All of these will render nothing for the disabled reason
// whitespace only
// prop not provided
```
--------------------------------
### Define Query Key Factory
Source: https://github.com/accesslayerorg/accesslayer-client/blob/dev/docs/adding-page-and-data-fetching.md
Define all React Query keys in a central factory at src/lib/queryKeys.ts to ensure predictable key shapes.
```ts
export const queryKeys = {
yourEntity: {
all: ['yourEntity'] as const,
list: (params?: GetYourParams) =>
['yourEntity', 'list', params ?? null] as const,
detail: (id: string) => ['yourEntity', 'detail', id] as const,
holders: (entityId: string) =>
['yourEntity', entityId, 'holders'] as const,
},
};
```
--------------------------------
### Define query key in src/lib/queryKeys.ts
Source: https://github.com/accesslayerorg/accesslayer-client/blob/dev/docs/api-layer.md
Add a unique cache key entry to ensure consistency across hooks referencing the same data.
```ts
// src/lib/queryKeys.ts
wallet: {
holdings: (address: string) => ['wallet', address, 'holdings'] as const,
// ...
},
```
--------------------------------
### Test the shared counter hook
Source: https://github.com/accesslayerorg/accesslayer-client/blob/dev/docs/shared-hooks.md
A test file for the counter hook located in src/hooks/__tests__/useCounter.test.ts using vitest and testing-library.
```ts
// src/hooks/__tests__/useCounter.test.ts
import { act, renderHook } from '@testing-library/react';
import { describe, expect, it } from 'vitest';
import { useCounter } from '@/hooks/useCounter';
describe('useCounter', () => {
it('increments from the initial value', () => {
const { result } = renderHook(() => useCounter(2));
act(() => result.current.increment());
expect(result.current.count).toBe(3);
});
});
```
--------------------------------
### Verify Query Key Shapes in Tests
Source: https://github.com/accesslayerorg/accesslayer-client/blob/dev/docs/react-query-cache-conventions.md
Unit tests for validating key structure and prefix sharing in src/lib/__tests__/queryKeys.test.ts.
```typescript
it('courses.detail shares the courses prefix with courses.all', () => {
expect(queryKeys.courses.detail('x')[0]).toBe(
queryKeys.courses.all[0],
);
});
it('courses.detail embeds the id at index 2', () => {
expect(queryKeys.courses.detail('course-123')[2]).toBe('course-123');
});
```
--------------------------------
### useMutation.onError pattern for API errors
Source: https://github.com/accesslayerorg/accesslayer-client/blob/dev/docs/error-handling-conventions.md
Demonstrates casting an error to ApiError and branching logic based on status codes to provide appropriate user feedback via toasts.
```ts
// src/hooks/useBuyCreatorKey.ts
import { useMutation, useQueryClient } from '@tanstack/react-query';
import { ApiError } from '@/services/api.service';
import showToast from '@/utils/toast.util';
import { queryKeys } from '@/lib/queryKeys';
import { creatorKeysService } from '@/services/creatorKeys.service';
export function useBuyCreatorKey() {
const queryClient = useQueryClient();
return useMutation({
mutationFn: ({
creatorId,
amount,
}: {
creatorId: string;
amount: number;
}) => creatorKeysService.buyKey(creatorId, amount),
onError: error => {
const apiError = error as ApiError;
// 1. Network failure — user is offline / server unreachable
if (apiError.status === 0) {
showToast.error(
'Network error. Check your connection and try again.'
);
return;
}
// 2. Server failure — not the user's fault; generic + retry
if (apiError.status >= 500) {
showToast.error(
'The server ran into a problem. Please try again shortly.'
);
return;
}
// 3. Validation — surface the first field error if present
if (apiError.status === 422 && apiError.response?.errors?.length) {
showToast.error(apiError.response.errors[0].message);
return;
}
// 4. Other 4xx — API message is safe for the user
showToast.error(apiError.message);
},
onSuccess: (_, { creatorId }) => {
queryClient.invalidateQueries({
queryKey: queryKeys.creators.detail(creatorId),
});
queryClient.invalidateQueries({ queryKey: queryKeys.wallet.all });
showToast.success('Key purchased successfully!');
},
});
}
```
--------------------------------
### Create CreatorListPage.tsx
Source: https://github.com/accesslayerorg/accesslayer-client/blob/dev/docs/adding-page-and-data-fetching.md
Defines the page component for listing creators, including loading states, error handling, and rendering the creator grid.
```tsx
// src/pages/CreatorListPage.tsx
import { useCreatorList } from '@/hooks/useCreatorList';
import CreatorCard from '@/components/common/CreatorCard';
import { CreatorCardGridSkeleton } from '@/components/common/CreatorCardSkeleton';
import { ApiError } from '@/services/api.service';
function CreatorListPageContent() {
const { data: creators, isLoading, error } = useCreatorList();
if (isLoading) {
return (
);
}
if (error) {
throw error;
}
if (!creators || creators.length === 0) {
throw new ApiError('No creators found', 404);
}
return (
All Creators
{creators.map(creator => (
))}
);
}
export default function CreatorListPage() {
return ;
}
```
--------------------------------
### Registering a new route in src/App.tsx
Source: https://github.com/accesslayerorg/accesslayer-client/blob/dev/docs/adding-page-routes.md
Add a new route by importing the page component and adding a path/element object to the createBrowserRouter array. Ensure the catch-all route remains the last entry.
```tsx
// src/App.tsx
import { createBrowserRouter, RouterProvider } from 'react-router';
import HomePage from './pages/HomePage';
import NotFoundPage from './pages/NotFoundPage';
import AboutPage from './pages/AboutPage'; // ← new import
const router = createBrowserRouter([
{
path: '/',
element: ,
},
{
path: '/about', // ← new public route
element: ,
},
{
path: '*', // catch-all stays last
element: ,
},
]);
```
--------------------------------
### Register route in App.tsx
Source: https://github.com/accesslayerorg/accesslayer-client/blob/dev/docs/adding-page-routes.md
Import the new page component and add it to the router array in src/App.tsx.
```tsx
// src/App.tsx
import HomePage from './pages/HomePage';
import NotFoundPage from './pages/NotFoundPage';
import AboutPage from './pages/AboutPage'; // ← added
const router = createBrowserRouter([
{ path: '/', element: },
{ path: '/about', element: }, // ← added
{ path: '*', element: },
]);
```
--------------------------------
### Marketplace search list read failure (Mode 2)
Source: https://github.com/accesslayerorg/accesslayer-client/blob/dev/docs/error-handling-conventions.md
Renders an inline error state with a retry button when the creator list query fails, keeping the rest of the page interactive.
```tsx
// src/pages/LandingPage.tsx (excerpt)
const { data: creators, isError, error, refetch } = useCreatorList();
if (isError) {
const apiError = error as ApiError;
return (
Couldn't load the creator list
{apiError.status >= 500
? 'Something went wrong on our end. Please try again.'
: apiError.message}
);
}
return ;
```
--------------------------------
### Handle Network Errors (status 0)
Source: https://github.com/accesslayerorg/accesslayer-client/blob/dev/docs/error-handling-in-hooks.md
Use this check when no response is received, indicating the user is offline, the server is unreachable, or a timeout occurred.
```ts
if (apiError.status === 0) {
showToast.error('Network error. Check your connection and try again.');
return;
}
```
--------------------------------
### Mocking the hook module wholesale
Source: https://github.com/accesslayerorg/accesslayer-client/blob/dev/docs/testing-conventions.md
Pattern for unit tests where the query machinery is considered noise and the hook module is mocked entirely.
```tsx
vi.mock('@/hooks/useWallet', () => ({
useTradeMutation: () => ({ mutateAsync: vi.fn(), isPending: false }),
useWalletHoldings: () => ({ data: [] }),
}));
```
--------------------------------
### Handling wallet signature rejection
Source: https://github.com/accesslayerorg/accesslayer-client/blob/dev/docs/error-handling-conventions.md
Uses a shared helper to detect wallet-side signature rejections and display a specific toast message.
```ts
// src/hooks/useWalletConnection.ts (excerpt)
import { getSignatureErrorMessage } from '@/utils/errorHandling.utils';
import showToast from '@/utils/toast.util';
onError: error => {
showToast.error(getSignatureErrorMessage(error));
// getSignatureErrorMessage returns either:
// - WALLET_ERROR_COPY.SIGNATURE_REJECTED (user clicked "Cancel")
// - WALLET_ERROR_COPY.SIGNATURE_FAILED (other wallet-side failure)
};
```
--------------------------------
### Consume Service in a Hook
Source: https://github.com/accesslayerorg/accesslayer-client/blob/dev/docs/adding-page-and-data-fetching.md
Import the service instance into a custom hook to manage data fetching with React Query.
```ts
// src/hooks/useYourData.ts
import { yourService } from '@/services/your.service';
export function useYourData(id: string) {
return useQuery({
queryKey: queryKeys.yourEntity.detail(id),
queryFn: () => yourService.getYourData(id),
enabled: !!id,
});
}
```
--------------------------------
### Consume Holdings in React Component
Source: https://github.com/accesslayerorg/accesslayer-client/blob/dev/docs/api-layer.md
Use the useWalletHoldings hook within a component to display loading, error, and data states.
```tsx
// Usage in any component
import { useAccount } from 'wagmi';
import { useWalletHoldings } from '@/hooks/useWalletHoldings';
function HoldingsSummary() {
const { address } = useAccount();
const { data: holdings, isLoading, error } = useWalletHoldings(address);
if (isLoading) return
Loading…
;
if (error) return
Could not load holdings.
;
if (!holdings?.length) return
No holdings yet.
;
return (
{holdings.map(h => (
{h.creatorId} — {h.quantity} keys at {h.priceStroops} stroops
))}
);
}
```
--------------------------------
### Invalidate queries with useQueryClient
Source: https://github.com/accesslayerorg/accesslayer-client/blob/dev/docs/state-management.md
Marks cached data as stale to trigger background refetching. Use this after mutations like buy, sell, or profile updates to ensure subscribers receive fresh data.
```ts
const queryClient = useQueryClient();
queryClient.invalidateQueries({ queryKey: queryKeys.creators.list() });
```
--------------------------------
### Service Method Error Handling
Source: https://github.com/accesslayerorg/accesslayer-client/blob/dev/docs/api-layer.md
Standard pattern for wrapping Axios calls in a try/catch block and re-throwing errors using the inherited handleError method.
```typescript
async getWalletHoldings(address: string): Promise {
try {
const response = await this.api.get>(
`/wallets/${address}/holdings`
);
return response.data.data;
} catch (error) {
throw this.handleError(error);
}
}
```