@freshworks/react-native-freshdesk-sdk
Version:
React Native wrapper for Freshdesk Android and iOS SDKs
144 lines (112 loc) • 4.66 kB
Markdown
# SDK Initialization
## Basic Initialization
Initialize the Freshdesk SDK as early as possible in your app lifecycle, typically in your root component:
```typescript
import React, { useEffect } from 'react';
import FreshdeskSDK from '@freshworks/react-native-freshdesk-sdk';
function App() {
useEffect(() => {
const initializeSDK = async () => {
try {
await FreshdeskSDK.initialize({
token: 'your_account_token',
host: 'your_host.freshdesk.com',
sdkId: 'your_sdk_id',
locale: 'en', // Optional: default is 'en'
});
console.log('Freshdesk SDK initialized');
} catch (error) {
console.error('Failed to initialize SDK:', error);
}
};
initializeSDK();
}, []);
return <YourApp />;
}
```
## Configuration Options
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `token` | string | Yes | Account token from Freshdesk portal |
| `host` | string | Yes | Freshdesk instance URL — `yourcompany.freshdesk.com` or `https://yourcompany.freshdesk.com` (auto-normalized) |
| `sdkId` | string | Yes | SDK ID from Freshdesk portal |
| `locale` | string | No | Locale for localization (default: 'en') |
| `jwt` | string | No | JWT token for user authentication |
| `debugMode` | boolean | No | Enable debug logging (Android only) |
## JWT Authentication
For JWT-enforced SDKs, you must provide a JWT token during initialization:
```typescript
await FreshdeskSDK.initialize({
token: 'your_account_token',
host: 'your_host.freshdesk.com',
sdkId: 'your_sdk_id',
jwt: 'your_jwt_token', // Required for JWT-enforced SDKs
});
```
### Updating JWT Token
To update a JWT token after initialization (e.g., after token refresh):
```typescript
await FreshdeskSDK.authenticateAndUpdate(newJwtToken);
```
## User Authentication States
Listen for user state changes to handle authentication scenarios:
```typescript
useEffect(() => {
const subscription = FreshdeskSDK.addUserStateListener((event) => {
console.log('User state:', event.state);
// Possible states: 'authenticated', 'authExpired', 'notAuthenticated', etc.
});
return () => {
subscription?.remove();
FreshdeskSDK.removeAllListeners();
};
}, []);
```
## User State Types
| State | Description |
|-------|-------------|
| `authenticated` | JWT passed is successfully authenticated |
| `authExpired` | JWT passed has expired |
| `notAuthenticated` | Invalid/Expired token is passed |
| `identifierUpdated` | Unique user identifier updated for a user |
| `jwtNotPresent` | JWT was not passed for an enforced JWT SDK |
| `undefined` | Default/initial state |
## Reset User
Call this when a user logs out to clear their session:
```typescript
const result = await FreshdeskSDK.resetUser();
console.log(result.success); // true if successful
```
> **iOS:** always resolves `{ success: true }` once initialized — the native
> SDK has no failure callback for reset. Only a call before `initialize()`
> resolved causes a rejection. See `PLATFORM_DIFFERENCES.md`.
## Important Notes
1. **Initialize once**: Call `initialize()` only once per app session
2. **Required before use**: All SDK methods require initialization first
3. **JWT-enforced SDKs**: Will fail to initialize without a valid JWT token
4. **User properties**: For non-JWT enforced SDKs, use `setUserProperties()` after initialization
5. **iOS takes ≥2 seconds**: `initialize()`'s promise resolves only once the
native SDK has had time to finish its own async loading — the native SDK
gives no completion signal of its own, so the wrapper waits instead of
letting a call right after `initialize()` race a load that isn't done
yet. This is expected, not a performance regression to fix. See
`PLATFORM_DIFFERENCES.md`.
## Error Handling
The SDK rejects with React Native's standard `NativeModule` error shape —
compare `error.code` against the typed `FreshdeskErrorCode` enum instead of
matching a message string:
```typescript
import { FreshdeskErrorCode } from '@freshworks/react-native-freshdesk-sdk';
try {
await FreshdeskSDK.initialize(config);
} catch (error) {
if (error.code === FreshdeskErrorCode.INVALID_CONFIG) {
// Handle missing required parameters
} else if (error.code === FreshdeskErrorCode.INIT_ERROR) {
// Handle initialization error
} else if (error.code === FreshdeskErrorCode.INIT_TIMEOUT) {
// Android only — verify token/host/sdkId, network, JWT settings
}
}
```
See [Error Codes Reference](troubleshooting.md#error-codes-reference) for the full list and which platform(s) emit each one.