Skip to content

Usage Examples

This page shows practical examples of how to use the different SDK components. Each example is designed to be clear and easy to implement.

1. Feedback Widget

Basic Configuration

typescript
import { Feedback } from './path-to/feedback';

const feedback = new Feedback({
  tracker: yourTrackerInstance,
  position: 'bottom-right',  // Button position
  themeColor: '#4f46e5',     // Primary color
  buttonText: 'Send Feedback',
  autoOpen: false            // Don't open automatically
});

// Show the form manually
feedback.open();

Screenshot Capture

typescript
// Configuration with screenshot
const feedbackWithScreenshot = new Feedback({
  tracker: yourTrackerInstance,
  screenshot: {
    enabled: true,
    allowEdit: true,
    quality: 0.8
  },
  onSubmit: (data) => {
    console.log('Feedback received:', data);
    // Here you can send the data to your backend
  }
});

2. Session Tracking

Basic Initialization

typescript
import { SessionTracker } from '@your-sdk/core';

const session = new SessionTracker({
  appId: 'your-app-id',
  sessionTimeout: 30, // minutes of inactivity
  recordClicks: true,
  recordScroll: true
});

// Start tracking
session.start();

// Add custom tags
session.addTag('userRole', 'premium');

Error Handling

typescript
// Error handling with context
try {
  // Code that might fail
} catch (error) {
  session.addErrorTag({
    message: error.message,
    stack: error.stack,
    component: 'CheckoutForm',
    action: 'processPayment',
    orderId: currentOrderId
  });
}

3. NPS (Net Promoter Score) Survey

Basic Configuration

typescript
import { NPS } from './path-to/nps';

const nps = new NPS({
  tracker: yourTrackerInstance,
  question: 'How likely are you to recommend our service?',
  themeColor: '#2563eb',
  position: 'bottom-center',
  autoShow: true,
  delay: 5000,  // Show after 5 seconds
  onRate: (score) => {
    console.log(`Score received: ${score}`);
    // Additional logic based on score
  }
});

Advanced Customization

typescript
const npsAdvanced = new NPS({
  // ...basic configuration...
  
  // Follow-up questions based on score
  followUpQuestions: {
    promoters: 'What do you like most about our service?',
    passives: 'How could we improve?',
    detractors: 'What could we do to improve your experience?'
  },
  
  // Color customization
  colors: {
    primary: '#4f46e5',
    text: '#1f2937',
    background: '#ffffff',
    buttonText: '#ffffff'
  }
});

4. Announcements and Notifications

Simple Notification

typescript
import { Announcement } from './path-to/announcement';

const announcement = new Announcement({
  tracker: yourTrackerInstance,
  title: 'New Feature Available!',
  message: 'Try our new improved search function',
  type: 'info',
  duration: 10000,  // Will hide after 10 seconds
  dismissible: true
});

Notification with Action

typescript
const announcementAction = new Announcement({
  title: 'Special Offer!',
  message: '50% off your next purchase',
  type: 'success',
  linkUrl: '/offers',
  linkText: 'View Offer',
  onClose: () => {
    console.log('User closed the notification');
  },
  onClick: () => {
    console.log('User clicked the notification');  
  }
});

5. Error Handling

Global Configuration

typescript
// In your main configuration file
window.onerror = function(message, source, lineno, colno, error) {
  if (session) {
    session.addErrorTag({
      message: message.toString(),
      stack: error?.stack || '',
      source: source,
      line: lineno,
      column: colno,
      url: window.location.href
    });
  }
  return false; // Allows other error handlers to run
};

Custom Error

typescript
function logError(error, context = {}) {
  if (session) {
    session.addErrorTag({
      message: error.message,
      stack: error.stack,
      ...context,
      timestamp: new Date().toISOString(),
      userAgent: navigator.userAgent
    });
  }
  
  // Optional: Send to monitoring service
  if (window.Sentry) {
    Sentry.captureException(error, { extra: context });
  }
}

6. Framework Integration

React

jsx
import { useEffect, useRef } from 'react';

export function FeedbackButton() {
  const feedbackRef = useRef(null);

  useEffect(() => {
    import('./path-to/feedback').then(module => {
      feedbackRef.current = new module.Feedback({
        tracker: yourTrackerInstance,
        // configuration...
      });
    });

    return () => {
      if (feedbackRef.current) {
        feedbackRef.current.destroy();
      }
    };
  }, []);

  return (
    <button onClick={() => feedbackRef.current?.open()}>
      Send Feedback
    </button>
  );
}

Vue 3

vue
<template>
  <button @click="openFeedback">Send Feedback</button>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue';

let feedback = ref(null);

onMounted(async () => {
  const module = await import('./path-to/feedback');
  feedback.value = new module.Feedback({
    tracker: yourTrackerInstance,
    // configuration...
  });
});

onUnmounted(() => {
  if (feedback.value) {
    feedback.value.destroy();
  }
});

const openFeedback = () => {
  if (feedback.value) {
    feedback.value.open();
  }
};
</script>

7. Event Tracking Example

typescript
// Tracker initialization
const tracker = new SystemTracker({
  appId: 'your-app-id',
  environment: process.env.NODE_ENV,
  version: '1.0.0'
});

// Example custom event
function trackButtonClick(buttonId) {
  tracker.trackEvent({
    category: 'UI Interaction',
    action: 'button_click',
    label: buttonId,
    value: 1
  });
}

// Example page view tracking
function trackPageView(pageName) {
  tracker.trackPageView({
    url: window.location.pathname,
    title: document.title,
    pageName: pageName
  });
}

8. Session Timeout Handling

typescript
// Set inactivity timeout (30 minutes)
const session = new SessionTracker({
  sessionTimeout: 30,
  onSessionTimeout: () => {
    console.log('Session has expired');
    // Show message to user
    new Announcement({
      title: 'Session Expired',
      message: 'Your session has expired due to inactivity',
      type: 'warning',
      duration: 0,
      dismissible: false
    });
  },
  onSessionRenew: () => {
    console.log('Session renewed');
  }
});

Conclusion

These examples cover the most common use cases for each SDK component. You can further customize each instance according to your application's specific needs. For more details, refer to each component's documentation.