> ## Documentation Index
> Fetch the complete documentation index at: https://docs.stackfront.digital/llms.txt
> Use this file to discover all available pages before exploring further.

# Events & Analytics

# Events & Analytics

The SDK includes a batched event tracking system that automatically collects lifecycle events and supports custom event tracking.

## How It Works

The `EventService` queues events in memory and flushes them in batches of 20 every 30 seconds:

1. `track()` adds an event to the pending queue
2. When the queue reaches 20 events, it flushes immediately
3. Every 30 seconds, any pending events are flushed
4. If a flush fails, events are persisted to AsyncStorage and retried on next init
5. On `StackfrontProvider` unmount, remaining events are flushed

## Automatic Events

| Event             | When                                     | Who      |
| ----------------- | ---------------------------------------- | -------- |
| `app_opened`      | SDK initialization complete              | Provider |
| `login`           | `useCustomer().login()` succeeds         | Hook     |
| `logout`          | `useCustomer().logout()` completes       | Hook     |
| `account_created` | `useCustomer().createAccount()` succeeds | Hook     |

## Custom Events

```tsx theme={null}
import { useStackfront } from 'react-native-stackfront-sdk';

function TrackButton() {
  const { events } = useStackfront();

  const handlePress = () => {
    events.track('button_tapped', {
      buttonName: 'cta_main',
      screen: 'home',
    });
  };

  return <Button title="Track Me" onPress={handlePress} />;
}
```

## Event Shape

```ts theme={null}
{
  eventType: string;                    // e.g. "app_opened", "button_tapped"
  platform: 'iOS' | 'Android';
  appVersion?: string;
  sessionId?: string;
  properties?: Record<string, unknown>; // arbitrary metadata
  occurredAt: string;                   // ISO timestamp
}
```

The `sessionId` is generated once when the provider mounts and persists for the app session.

## Service API

```ts theme={null}
const { events } = useStackfront();

// Track immediately
events.track('purchase_completed', { orderId: '123', total: 49.99 });

// Manually flush pending events
await events.flush();
```

## Best Practices

* Use descriptive event names in `snake_case`
* Limit properties to primitive types and flat structures
* Avoid tracking personally identifiable information (PII) in properties
* The event pipeline is fire-and-forget — errors are silently handled and retried
