Events & Monitoring

The SDK provides a comprehensive event system for monitoring component loading, cache operations, and errors.

Event Emitter

Subscribe to events using the dpage event emitter:

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

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

// Later: cleanup
unsubscribe();

// Or remove all listeners
dpage.off();

Available Events

EventDescriptionPayload
fetchStartAPI request started{componentKey}
fetchSuccessAPI request succeeded{componentKey, durationMs}
fetchErrorAPI request failed{componentKey, error}
cacheHitComponent loaded from cache{componentKey}
cacheMissComponent not in cache{componentKey}
cacheWriteComponent written to cache{componentKey}
fallbackFell back to error state{componentKey, reason}

Usage Examples

Analytics Integration

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

// Track fetch performance
dpage.on('fetchSuccess', (e) => {
  analytics.track('dpage_fetch_success', {
    component: e.componentKey,
    duration_ms: e.durationMs,
  });
});

// Track errors
dpage.on('fetchError', (e) => {
  analytics.track('dpage_fetch_error', {
    component: e.componentKey,
    error: e.error.message,
  });
});

// Track cache efficiency
dpage.on('cacheHit', (e) => {
  analytics.track('dpage_cache_hit', {
    component: e.componentKey,
  });
});

Error Monitoring (Sentry)

TSX
import * as Sentry from '@sentry/react-native';
import { dpage } from '@dpage-ai/react-native-dpage';

dpage.on('fetchError', (e) => {
  Sentry.captureException(e.error, {
    tags: { component: e.componentKey },
    extra: { event: 'dpage_fetch_error' },
  });
});

dpage.on('fallback', (e) => {
  Sentry.captureMessage(`Component fallback: ${e.componentKey}`, {
    level: 'warning',
    extra: { reason: e.reason },
  });
});

Custom Logging

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

dpage.on('fetchStart', (e) => {
  console.log(`[DPage] Fetching: ${e.componentKey}`);
});

dpage.on('fetchSuccess', (e) => {
  console.log(`[DPage] Loaded ${e.componentKey} in ${e.durationMs}ms`);
});

dpage.on('cacheHit', (e) => {
  console.log(`[DPage] Cache hit: ${e.componentKey}`);
});

dpage.on('cacheMiss', (e) => {
  console.log(`[DPage] Cache miss: ${e.componentKey}`);
});

Cleaning Up Listeners

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

function App() {
  useEffect(() => {
    const unsubscribe1 = dpage.on('fetchError', handleError);
    const unsubscribe2 = dpage.on('cacheHit', trackCacheHit);

    return () => {
      unsubscribe1();
      unsubscribe2();
    };
  }, []);

  return <YourApp />;
}

Memory Leaks

Always unsubscribe from events when components unmount to prevent memory leaks.

Performance Monitoring

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

// Track load times
const loadTimes: Record<string, number[]> = {};

dpage.on('fetchSuccess', (e) => {
  if (!loadTimes[e.componentKey]) {
    loadTimes[e.componentKey] = [];
  }
  loadTimes[e.componentKey].push(e.durationMs);
});

// Calculate averages
function getAverageLoadTime(componentKey: string): number {
  const times = loadTimes[componentKey] || [];
  if (times.length === 0) return 0;
  return times.reduce((a, b) => a + b, 0) / times.length;
}

Debug Logging

Enable verbose logging with the logLevel config:

TSX
initDPage({
  projectId: 'my-project',
  apiToken: 'xxx',
  logLevel: 'debug', // 'none' | 'error' | 'warn' | 'info' | 'debug'
});

// Console output:
// [DynamicComponentCache] Cache hit: ProductCard
// [DynamicComponentService] Fetch start: NewComponent
// [DynamicComponentService] Fetch success: NewComponent (234ms)
// [DynamicComponentCache] Cache write: NewComponent

Best Practices

Register events early

Set up event listeners at app initialization to capture all events.

Clean up listeners

Always unsubscribe when components unmount to prevent memory leaks.

Keep handlers lightweight

Event handlers run on the JS thread. Avoid blocking operations.

Use for observability

Feed events to analytics, logging, and monitoring systems.