SDK

API Reference

Complete reference for all public exports from @dpage-ai/react-native-dpage.

Configuration

initDPage(config)

Initialize the SDK with configuration. Call once at app startup.

TSX
import { initDPage } from '@dpage-ai/react-native-dpage';

initDPage({
  projectId: 'my-project',
  apiToken: 'dpage_live_xxx',
  fetch: { timeout: 10000 },
  cache: { ttl: 3600000 },
  logLevel: 'warn',
});

resetDPageConfig()

Reset configuration to defaults. Clears all settings including apiToken.

TSX
import { resetDPageConfig } from '@dpage-ai/react-native-dpage';

resetDPageConfig();

getProjectId()

Get the current project ID.

TSX
import { getProjectId } from '@dpage-ai/react-native-dpage';

const projectId = getProjectId();

isInitialized()

Check if the SDK has been initialized.

TSX
import { isInitialized } from '@dpage-ai/react-native-dpage';

if (isInitialized()) {
  // SDK is ready
}

initLifecycleListener()

Enable automatic state saves when app goes to background. Call once at app startup after initDPage().

TSX
import { initLifecycleListener } from '@dpage-ai/react-native-dpage';

// Call once at app startup
initLifecycleListener();

setDeviceId(id)

Set the device identifier for anonymous state sync.

TSX
import { setDeviceId } from '@dpage-ai/react-native-dpage';

setDeviceId('device-uuid-here');

setUserAuth(auth)

Set or clear user authentication for cloud sync. Pass { userId, authToken } on login, or null on logout.

TSX
import { setUserAuth } from '@dpage-ai/react-native-dpage';

// On login
setUserAuth({ userId: user.id, authToken: session.access_token });

// On logout
setUserAuth(null);

isCloudSyncEnabled()

Check if cloud sync is enabled in the config.

TSX
import { isCloudSyncEnabled } from '@dpage-ai/react-native-dpage';

if (isCloudSyncEnabled()) {
  // Cloud sync is active
}

isErrorReportingEnabled()

Check if error reporting is enabled in the config.

TSX
import { isErrorReportingEnabled } from '@dpage-ai/react-native-dpage';

if (isErrorReportingEnabled()) {
  // Error reporting is active
}

Components

DynamicComponent

Render a server-driven component by name.

TSX
import React, { useMemo } from 'react';
import { DynamicComponent } from '@dpage-ai/react-native-dpage';

const editModeDeps = useMemo(
  () => ({
    // Override View/Text/etc for edit mode (example)
    // View: EditableView,
  }),
  []
);

<DynamicComponent
  name="ProductCard"           // Required: component name
  data={{ productId: '123' }}  // Optional: props for the component
  projectId="override"         // Optional: override project ID
  miniappId="my-miniapp"       // Optional: for error reporting
  miniappVersion="1.2.3"       // Optional: included in error reports
  renderLoading={() => <Loader />}  // Optional: custom loading
  renderError={(e) => <Error error={e} />}  // Optional: custom error
  runtimeDepsOverrides={editModeDeps} // Optional: per-render runtime deps overrides
/>

Keep overrides object identity stable

runtimeDepsOverrides should be a stable object (hoist it or create it via useMemo). A new object every render bypasses caching and recompiles the component.

MiniappComponent

Render a miniapp (collection of components) by ID.

TSX
import React, { useMemo } from 'react';
import { MiniappComponent } from '@dpage-ai/react-native-dpage';

const editModeDeps = useMemo(
  () => ({
    Modal: InlineModal,
  }),
  []
);

<MiniappComponent
  miniappId="checkout-flow"    // Required: miniapp ID
  renderLoading={() => <Loader />}  // Optional: custom loading
  renderError={(e) => <Error error={e} />}  // Optional: custom error
  onLoaded={(result) => console.log(result)}  // Optional: callback
  runtimeDepsOverrides={editModeDeps} // Optional: per-render runtime deps overrides
/>

ErrorBoundary

A React error boundary for catching runtime errors. Automatically reports errors to the DPage server when miniappId is provided. Both MiniappComponent and DynamicComponent include this automatically.

TSX
import { ErrorBoundary } from '@dpage-ai/react-native-dpage';

// With retry/go-back handlers (shows default error UI with buttons)
<ErrorBoundary
  miniappId="checkout-flow"
  miniappVersion="1.0.0"
  onRetry={() => setRetryKey(k => k + 1)}
  onGoBack={() => navigation.goBack()}
>
  <MyContent />
</ErrorBoundary>

// With custom fallback UI
<ErrorBoundary
  miniappId="checkout-flow"
  fallback={(error, reset) => (
    <View>
      <Text>Error: {error.message}</Text>
      <Button onPress={reset} title="Try Again" />
    </View>
  )}
>
  <MyContent />
</ErrorBoundary>

Hooks

useDynamicComponent(name, options?)

Load a dynamic component programmatically.

TSX
import React, { useMemo } from 'react';
import { useDynamicComponent } from '@dpage-ai/react-native-dpage';

const editModeDeps = useMemo(
  () => ({
    View: EditableView,
  }),
  []
);

const {
  Component,  // React.ComponentType | null
  loading,    // boolean
  error,      // Error | null
  reload,     // () => void - reload from cache
  refresh,    // () => void - force refresh from API
} = useDynamicComponent('ComponentName', {
  projectId: 'optional-override',
  runtimeDepsOverrides: editModeDeps,
});

useNamedPersistentState(key, initialValue)

A useState-like hook for persistent state that survives app restarts. Must be used inside a MiniappStateProvider.

TSX
import { useNamedPersistentState } from '@dpage-ai/react-native-dpage';

function Counter() {
  const [count, setCount] = useNamedPersistentState('count', 0);
  
  return (
    <Button onPress={() => setCount(c => c + 1)}>
      Count: {count}
    </Button>
  );
}

Preloading

FunctionDescription
preloadComponent(name, projectId?)Preload a single component into cache
preloadComponents(names, projectId?)Preload multiple components into cache
refreshComponent(name, projectId?)Force refresh a component from API, bypassing cache

Cache Management

clearCache(options?)

Clear cached components.

TSX
import { clearCache } from '@dpage-ai/react-native-dpage';

// Clear all
await clearCache();

// Clear by name
await clearCache({ name: 'ProductCard' });

// Clear by project
await clearCache({ projectId: 'my-project' });

// Clear specific component in project
await clearCache({ name: 'ProductCard', projectId: 'my-project' });

getCacheStats(projectId?)

Get cache statistics.

TSX
import { getCacheStats } from '@dpage-ai/react-native-dpage';

const stats = await getCacheStats();
console.log(`Cached: ${stats.count} components`);
console.log('Keys:', stats.keys);

clearMiniappCache(miniappId, projectId?)

Clear all cached components for a specific miniapp.

TSX
import { clearMiniappCache } from '@dpage-ai/react-native-dpage';

await clearMiniappCache('my-miniapp-id');

Persistent State

PersistenceManager

API for managing persistent state storage. See the Persistent State guide for full details.

FunctionDescription
restoreMiniapp(appId)Load state from AsyncStorage into memory
saveMiniapp(appId)Save miniapp state to AsyncStorage
saveAll()Save all active miniapp states
clearMiniapp(appId)Clear state for a miniapp
clearMiniappData(appId)Clear state + cache for a miniapp
clearAllData()Clear all state + cache
getSyncStatus(appId)Get sync status (lastLocalSave, lastCloudSync)
getUnsyncedMiniapps()Get list of miniapps with unsynced changes
markSynced(appId)Mark a miniapp as synced after cloud upload
setSyncCallbacks(callbacks)Register cloud sync callbacks

CloudSync

Built-in client for DPage cloud sync. Uses your configured authToken.

TSX
import { CloudSync } from '@dpage-ai/react-native-dpage';

// Upload state to cloud
await CloudSync.upload(miniappId, snapshot);

// Download state from cloud
const { found, state, version } = await CloudSync.download(miniappId);

// Batch operations
await CloudSync.uploadBatch([{ miniappId, snapshot }, ...]);
const { states } = await CloudSync.downloadBatch([id1, id2]);

Events

dpage.on(event, callback)

Subscribe to an event. Returns an unsubscribe function.

TSX
import { dpage } from '@dpage-ai/react-native-dpage';

const unsubscribe = dpage.on('fetchStart', (e) => {
  console.log('Fetching:', e.componentKey);
});

// Later: cleanup
unsubscribe();

dpage.off(event?)

Unsubscribe from events.

TSX
import { dpage } from '@dpage-ai/react-native-dpage';

// Remove all listeners for an event
dpage.off('fetchStart');

// Remove all listeners
dpage.off();

Error Classes

HttpError

Thrown when an HTTP request fails with a non-2xx status.

TSX
import { HttpError } from '@dpage-ai/react-native-dpage';

try {
  await refreshComponent('MyComponent');
} catch (error) {
  if (error instanceof HttpError) {
    console.log(`HTTP ${error.status}: ${error.statusText}`);
  }
}

FetchTimeoutError

Thrown when a request times out.

TSX
import { FetchTimeoutError } from '@dpage-ai/react-native-dpage';

try {
  await refreshComponent('MyComponent');
} catch (error) {
  if (error instanceof FetchTimeoutError) {
    console.log('Request timed out');
  }
}

Error Reporting

Report miniapp runtime errors to the DPage dashboard for monitoring and debugging. Errors are automatically associated with the miniapp and include platform info, stack traces, and optional metadata.

reportMiniappError(report)

Reports a runtime error to the DPage server. Returns a promise with the result.

TSX
import { reportMiniappError } from '@dpage-ai/react-native-dpage';

const result = await reportMiniappError({
  miniappId: 'abc-123',
  errorMessage: 'Cannot read property "foo" of undefined',
  errorStack: error.stack,
  componentStack: errorInfo?.componentStack,
  miniappVersion: '1.2.3',  // Optional: version of the miniapp
  metadata: {               // Optional: custom metadata
    userId: 'user-123',
    action: 'submit_form',
  },
});

if (result.success) {
  console.log('Error reported:', result.errorId);
} else {
  console.log('Failed to report:', result.error);
}

createMiniappErrorReporter(miniappId, miniappVersion?)

Creates a reusable error reporter function bound to a specific miniapp. Useful for error boundaries.

TSX
import { createMiniappErrorReporter } from '@dpage-ai/react-native-dpage';

// Create a reporter bound to a miniapp
const reportError = createMiniappErrorReporter('abc-123', '1.2.3');

// Use in error boundary
class MyErrorBoundary extends React.Component {
  componentDidCatch(error: Error, errorInfo: React.ErrorInfo) {
    // Fire and forget - won't throw
    reportError(error, errorInfo.componentStack, {
      userId: 'user-123',
    });
  }
}

Note: Error reporting requires a valid apiToken to be configured. Errors are sent to the DPage server and can be viewed in the miniapp's dashboard under the "Errors" tab.

Types

DPageConfig

TypeScript
interface DPageConfig {
  projectId: string;
  apiToken?: string;
  cloudSync?: boolean;           // Enable cloud state sync
  errorReporting?: boolean;      // Enable error reporting (default: true)
  deviceId?: string;             // Device identifier
  userAuth?: {                   // User authentication
    userId: string;
    authToken: string;
  };
  fetch?: {
    enabled?: boolean;
    timeout?: number;
    baseUrl?: string;
    customFetch?: typeof fetch;
    requestTransform?: (params: RequestTransformParams) => RequestTransformResult;
  };
  cache?: {
    enabled?: boolean;
    ttl?: number;
    namespace?: string;
  };
  runtimeDeps?: Record<string, unknown>;
  logLevel?: 'none' | 'error' | 'warn' | 'info' | 'debug';
}

DynamicComponentProps

TypeScript
interface DynamicComponentProps<K extends string> {
  name: K;
  data?: ComponentPropsMap[K];
  projectId?: string;
  miniappId?: string;              // For error reporting and cache scoping
  miniappVersion?: string;         // Included in error reports
  renderLoading?: () => React.ReactNode;
  renderError?: (error: Error) => React.ReactNode;
  runtimeDepsOverrides?: Record<string, unknown>; // Keep object identity stable (useMemo/hoist)
}

ErrorBoundaryProps

TypeScript
interface ErrorBoundaryProps {
  children: React.ReactNode;
  /** Miniapp ID for automatic error reporting */
  miniappId?: string;
  /** Miniapp version included in error reports */
  miniappVersion?: string;
  /** Custom error UI. Receives the error and a reset function. */
  fallback?: (error: Error, reset: () => void) => React.ReactNode;
  /** Callback when an error is caught */
  onError?: (error: Error, componentStack: string) => void;
  /** Shows "Try Again" button when provided */
  onRetry?: () => void;
  /** Shows "Go Back" button when provided */
  onGoBack?: () => void;
  /** Enable/disable error reporting. Defaults to true when miniappId is set. */
  reportErrors?: boolean;
}

UseDynamicComponentResult

TypeScript
interface UseDynamicComponentResult {
  Component: React.ComponentType | null;
  loading: boolean;
  error: Error | null;
  reload: () => void;
  refresh: () => void;
}

CacheStats

TypeScript
interface CacheStats {
  count: number;
  keys: string[];
}

Event Types

TypeScript
type DPageEvent =
  | 'fetchStart'
  | 'fetchSuccess'
  | 'fetchError'
  | 'cacheHit'
  | 'cacheMiss'
  | 'cacheWrite'
  | 'cacheClear'
  | 'cacheInvalid'
  | 'fallback';

interface FetchStartEvent {
  componentKey: string;
}

interface FetchSuccessEvent {
  componentKey: string;
  durationMs: number;
}

interface FetchErrorEvent {
  componentKey: string;
  error: Error;
}

Error Reporting Types

TypeScript
// Error report payload
interface ErrorReport {
  miniappId: string;
  errorMessage: string;
  errorStack?: string;
  componentStack?: string;
  miniappVersion?: string;       // Version of the miniapp
  metadata?: Record<string, unknown>;
}

// Response from reportMiniappError
interface ErrorReportResponse {
  success: boolean;
  errorId?: string;              // Unique ID for the reported error
  createdAt?: string;            // Timestamp when recorded
  error?: string;                // Error message if failed
}

Persistent State Types

TypeScript
// Serializable state values
type StateValue =
  | string
  | number
  | boolean
  | null
  | StateValue[]
  | { [key: string]: StateValue };

// State snapshot for a miniapp
interface StateSnapshot {
  version: number;
  timestamp: number;
  state: Record<string, StateValue>;
  lastLocalSave: number;
  lastCloudSync: number;
}

// Sync status for a miniapp
interface SyncStatus {
  miniappId: string;
  lastLocalSave: number;
  lastCloudSync: number;
  needsSync: boolean;
}

// Cloud sync callbacks
interface CloudSyncCallbacks {
  onMiniappClose?: (miniappId: string) => Promise<void>;
  onAppForeground?: () => Promise<void>;
  onAppBackground?: () => Promise<void>;
}

Default Export

The package has a default export that is the DynamicComponent:

TSX
import DynamicComponent from '@dpage-ai/react-native-dpage';

// Same as:
import { DynamicComponent } from '@dpage-ai/react-native-dpage';