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

# React SDK

> Learn how to integrate Suada with your React application

## Overview

The Suada React SDK provides a seamless way to integrate Suada's AI capabilities into your React applications. Built with modern React practices in mind, it offers hooks, components, and utilities that make it easy to add AI-powered features to your application.

## Prerequisites

* React 16.8.0 or higher (for Hooks support)
* Node.js 16.0.0 or higher
* A Suada API key
* npm or yarn package manager

## Installation

Install the Suada React SDK and its peer dependencies:

```bash theme={null}
# Using npm
npm install @suada/react @suada/core

# Using yarn
yarn add @suada/react @suada/core
```

## Quick Start

Here's a basic example to get you started:

```tsx theme={null}
import { SuadaProvider, ChatComponent } from '@suada/react';

function App() {
  return (
    <SuadaProvider
      config={{
        apiKey: process.env.REACT_APP_SUADA_API_KEY
      }}
    >
      <ChatComponent
        onMessageSubmit={(message) => console.log('Message sent:', message)}
        onResponseReceived={(response) => console.log('Response:', response)}
      />
    </SuadaProvider>
  );
}
```

## Authentication

### Setting up your API Key

We recommend storing your API key in environment variables:

```env theme={null}
# .env.local
REACT_APP_SUADA_API_KEY=your-api-key
```

For production, ensure you're using appropriate environment configuration:

```env theme={null}
# .env.production
REACT_APP_SUADA_API_KEY=your-production-api-key
REACT_APP_SUADA_BASE_URL=https://api.suada.ai
```

### Configuring the Provider

Wrap your application with `SuadaProvider`:

```tsx theme={null}
import { SuadaProvider } from '@suada/react';

function App() {
  return (
    <SuadaProvider
      config={{
        apiKey: process.env.REACT_APP_SUADA_API_KEY,
        baseUrl: process.env.REACT_APP_SUADA_BASE_URL,
        debug: process.env.NODE_ENV === 'development'
      }}
    >
      <YourApp />
    </SuadaProvider>
  );
}
```

## Core Components

### Chat Component

A pre-built chat interface component:

```tsx theme={null}
import { ChatComponent } from '@suada/react';

function ChatInterface() {
  return (
    <ChatComponent
      theme="light"
      placeholder="Ask a question..."
      initialMessages={[]}
      privacyMode={true}
      onMessageSubmit={(message) => {
        console.log('Message:', message);
      }}
      onResponseReceived={(response) => {
        console.log('Response:', response);
      }}
    />
  );
}
```

#### Props

| Prop               | Type                         | Required | Description                        |
| ------------------ | ---------------------------- | -------- | ---------------------------------- |
| theme              | 'light' \| 'dark'            | No       | UI theme (defaults to 'light')     |
| placeholder        | string                       | No       | Input placeholder text             |
| initialMessages    | Message\[]                   | No       | Pre-loaded chat messages           |
| privacyMode        | boolean                      | No       | Enable enhanced privacy features   |
| onMessageSubmit    | (message: string) => void    | Yes      | Called when a message is submitted |
| onResponseReceived | (response: Response) => void | Yes      | Called when a response is received |
| onError            | (error: Error) => void       | No       | Called when an error occurs        |

### Integration Components

#### Integration Manager

The main component for managing integrations:

```tsx theme={null}
import { IntegrationManager } from '@suada/react';

function IntegrationsPage() {
  return (
    <IntegrationManager
      onIntegrationConnected={(integration) => {
        console.log(`${integration.provider} connected`);
      }}
      onIntegrationDisconnected={(integration) => {
        console.log(`${integration.provider} disconnected`);
      }}
      layout="grid"
      className="custom-integration-manager"
    />
  );
}
```

#### Integration Button

A standalone button for connecting services:

```tsx theme={null}
import { IntegrationButton } from '@suada/react';

function ConnectButton() {
  return (
    <IntegrationButton
      provider="notion"
      redirectUri="https://your-app.com/callback"
      onSuccess={(result) => console.log('Connected:', result)}
      onError={(error) => console.error('Error:', error)}
    />
  );
}
```

## Hooks

### useSuada

The main hook for accessing Suada functionality:

```tsx theme={null}
import { useSuada } from '@suada/react';

function ChatFeature() {
  const { sendMessage, isLoading, error } = useSuada();

  const handleSend = async () => {
    try {
      const response = await sendMessage({
        message: "What's the latest update?",
        privacyMode: true
      });
      console.log('Response:', response);
    } catch (error) {
      console.error('Error:', error);
    }
  };

  return (
    <div>
      <button onClick={handleSend} disabled={isLoading}>
        Send Message
      </button>
      {error && <p>Error: {error.message}</p>}
    </div>
  );
}
```

### useIntegrations

Manage integrations programmatically:

```tsx theme={null}
import { useIntegrations } from '@suada/react';

function IntegrationsFeature() {
  const { 
    connect, 
    disconnect, 
    integrations,
    isConnecting 
  } = useIntegrations();

  return (
    <div>
      {integrations.map((integration) => (
        <div key={integration.id}>
          <span>{integration.provider}</span>
          <button 
            onClick={() => disconnect(integration.id)}
            disabled={isConnecting}
          >
            Disconnect
          </button>
        </div>
      ))}
    </div>
  );
}
```

## Error Handling

The SDK provides typed errors for better error handling:

```tsx theme={null}
import { SuadaError, SuadaAPIError } from '@suada/core';

try {
  await sendMessage({ message: "Hello" });
} catch (error) {
  if (error instanceof SuadaAPIError) {
    // Handle API-specific errors
    console.error('API Error:', error.message, error.status);
  } else if (error instanceof SuadaError) {
    // Handle general SDK errors
    console.error('SDK Error:', error.message);
  } else {
    // Handle unexpected errors
    console.error('Unexpected error:', error);
  }
}
```

## Best Practices

### Security

* Store API keys in environment variables
* Use privacy mode for sensitive data
* Implement proper error boundaries
* Secure OAuth callback endpoints

### Performance

* Implement proper cleanup in useEffect
* Use memoization for expensive computations
* Implement proper error boundaries
* Consider implementing request caching

### Development

* Use TypeScript for better type safety
* Follow React best practices
* Write unit tests
* Keep dependencies updated

## FAQ

### How do I handle environment-specific configuration?

Use environment files and ensure they're properly configured:

```env theme={null}
# .env.development
REACT_APP_SUADA_API_KEY=your-dev-key
REACT_APP_SUADA_BASE_URL=https://dev-api.suada.ai

# .env.production
REACT_APP_SUADA_API_KEY=your-prod-key
REACT_APP_SUADA_BASE_URL=https://api.suada.ai
```

### How do I customize component themes?

You can override the default styles using CSS variables:

```css theme={null}
:root {
  --suada-primary-color: #007bff;
  --suada-background-color: #ffffff;
  --suada-text-color: #333333;
}
```

### Can I use the SDK with Next.js?

Yes, the SDK is compatible with Next.js. For server components, use the appropriate imports:

```tsx theme={null}
'use client';
import { SuadaProvider } from '@suada/react';
```

### How do I implement retry logic?

The SDK includes built-in retry logic that you can configure:

```tsx theme={null}
<SuadaProvider
  config={{
    apiKey: process.env.REACT_APP_SUADA_API_KEY,
    maxRetries: 3,
    retryDelay: 1000
  }}
>
  <YourApp />
</SuadaProvider>
```

### How can I debug the SDK?

Enable debug mode in your provider configuration:

```tsx theme={null}
<SuadaProvider
  config={{
    apiKey: process.env.REACT_APP_SUADA_API_KEY,
    debug: true
  }}
>
  <YourApp />
</SuadaProvider>
```

## Support & Resources

### Documentation

* [API Reference](/api-reference)
* [Component Library](/components)
* [Integration Guides](/guides)

### Support

* Email Support: [hello@suada.ai](mailto:hello@suada.ai)
