captainup-react-native-sdk
v1.1.2
Published
CaptainUp Gamification SDK for React Native
Maintainers
Readme
CaptainUp React Native SDK
Gamification SDK for React Native apps. Add badges, levels, leaderboards, rewards, and real-time notifications to your app.
Installation
npm install captainup-react-native-sdkPeer Dependencies
npm install react react-nativeQuick Start
import CaptainUp, { CaptainUpEvents, LeaderboardTime } from 'captainup-react-native-sdk';
// 1. Connect
await CaptainUp.connect({
url: 'https://captainup.com',
apiKey: 'YOUR_API_KEY',
mobileToken: 'YOUR_MOBILE_TOKEN',
debugLogs: false,
});
// 2. Authenticate
await CaptainUp.authenticate({
userId: 'user-123',
name: 'John',
});
// Or use the convenience method:
await CaptainUp.connectAndAuthenticate(
{ url: 'https://captainup.com', apiKey: '...', mobileToken: '...' },
{ userId: 'user-123', name: 'John' },
);API Reference
Lifecycle
| Method | Description |
|--------|-------------|
| connect(options) | Initialize SDK and connect to server. |
| authenticate(userData) | Authenticate a user. Call after connect(). |
| connectAndAuthenticate(options, userData) | Connect and authenticate in one call. |
| disconnect() | Disconnect and reset all state. |
| refresh() | Refresh application and user data. |
| refreshAppData() | Refresh only application data. |
| isConnected() | Check if SDK is connected. |
| isAuthenticated() | Check if a user is authenticated. |
| getSDKVersion() | Get the SDK version string. |
User
const user = CaptainUp.getLoggedInUser();
// Perform an action
await user.performAction({ name: 'visit' });
// With entity
await user.performAction({
name: 'visit',
entity: { name: 'page', url: 'https://example.com' },
});
// Update user profile
await user.updateName('New Name');
await user.updateImageUrl('https://example.com/avatar.png');Application Data
const app = CaptainUp.getApplication();
CaptainUp.getBadges(); // All badges
CaptainUp.getAssets(); // All assets
CaptainUp.getAssetsByType('shop_item'); // Filtered by type
CaptainUp.getLevels(); // All levels
CaptainUp.getActionSettings(); // Action settings
CaptainUp.getCurrencySettings(); // Currency settings
// Segmented (filtered by user's segmentation rules)
CaptainUp.getSegmentedBadges();
CaptainUp.getSegmentedAssets();
CaptainUp.getSegmentedAssetsByType('trophy');Leaderboard
const result = await CaptainUp.queryLeaderboard({
time: LeaderboardTime.ALL_TIME, // ALL_TIME | MONTHLY | WEEKLY | DAILY
skip: 0,
limit: 20,
});
result.entries.forEach(entry => {
console.log(`#${entry.requestedLeaderboardPosition} ${entry.name} - ${entry.currencies.points} pts`);
});LeaderboardTime constants:
LeaderboardTime.ALL_TIME—'all_time_ranking'LeaderboardTime.MONTHLY—'monthly_ranking'LeaderboardTime.WEEKLY—'weekly_ranking'LeaderboardTime.DAILY—'daily_ranking'
Player / Activity Feed
const feed = await CaptainUp.queryPlayerFeed('user-123');
feed.items.forEach(item => {
console.log(item.action.name, item.userName);
});Inbox
const user = CaptainUp.getLoggedInUser();
const inbox = user.inbox;
// Fetch unread IDs first for accurate read/unread status
await inbox.checkForNewMessages();
// Query messages
const items = await inbox.query({ limit: 20 });
items.forEach(item => {
console.log(item.title, item.message, item.isUnread, item.presetImage);
});
// Unread counts
inbox.getNewMessageCount();
inbox.getUnreadInboxMessages();
inbox.getUnreadInboxNotifications();
// Mark as read
await inbox.markMessageAsRead(item.id);
await inbox.markAllAsRead();
// Listen for new messages
const listener = {
onNewInboxMessages(messages) { /* ... */ },
onNewInboxNotification(notifications) { /* ... */ },
onInboxError(error) { /* ... */ },
};
inbox.addListener(listener);
inbox.removeListener(listener);Rewards
const user = CaptainUp.getLoggedInUser();
// Get available rewards
const rewards = user.getAvailableRewards();
// Claim a reward
await user.claimReward(reward, badgeId);Assets
const user = CaptainUp.getLoggedInUser();
// Acquire an asset
await user.acquireAsset(asset);
// Get acquired assets
const acquired = user.getAcquiredAssets();Localization
CaptainUp.setLanguageCode('es-es'); // Language: 'en-us', 'es-es', 'fr-fr', 'el-gr', etc.
CaptainUp.setCountry('US'); // Country: 'US', 'GB', 'DE', etc. (uppercase ISO 3166)
CaptainUp.setCurrency('EUR'); // Currency: 'USD', 'EUR', 'GBP', etc. (uppercase ISO 4217)Can be called before or after connect().
App Lifecycle
import { AppState } from 'react-native';
AppState.addEventListener('change', (state) => {
if (state === 'active') {
CaptainUp.onAppBecameActive(); // Reconnect socket + check inbox
} else if (state === 'background') {
CaptainUp.onAppEnteredBackground(); // Disconnect socket after 10s
}
});Events
import CaptainUp, { CaptainUpEvents } from 'captainup-react-native-sdk';
// Subscribe (returns unsubscribe function)
const unsubscribe = CaptainUp.on(CaptainUpEvents.BADGES_ACHIEVED, ({ badges }) => {
console.log('Badges earned:', badges);
});
// Unsubscribe
unsubscribe();
// Or manually
CaptainUp.off(CaptainUpEvents.BADGES_ACHIEVED, handler);Available events:
| Event | Payload | Description |
|-------|---------|-------------|
| AFTER_CONNECT | application | SDK connected to server. |
| APP_DATA_UPDATED | application | Application data refreshed. |
| AUTHENTICATION_DONE | ActionableUser | User authenticated. |
| ERROR | Error | Connection/auth error. |
| BADGES_ACHIEVED | { user, badges } | User earned badge(s). |
| LEVELS_ACHIEVED | { user, levels } | User advanced level(s). |
| BADGE_PROGRESS | { user, progressMap } | Badge progress changed. |
| CURRENCY_RECEIVED | { user, currency, amount } | Currency received. |
| LEADERBOARD_CHANGED | { user, positions } | Leaderboard position changed. |
| ASSET_ACQUIRED | { user, asset } | User acquired an asset. |
| TROPHY_ACHIEVED | { user, asset } | Trophy-type asset achieved. |
| SHOP_ITEM_ACQUIRED | { user, asset } | Shop item acquired. |
| REWARD_AVAILABLE | { user, reward, badge } | New reward available to claim. |
| ACTION_PROCESSED | { user, action } | Action processed (via WebSocket). |
| USER_ERROR | { user, error } | User operation error. |
| SOCKET_CONNECTED | — | WebSocket opened. |
| SOCKET_DISCONNECTED | — | WebSocket closed. |
| ACTION_RESPONSE | response | Raw action response from WebSocket. |
| INBOX_ERROR | Error | Inbox operation error. |
| NEW_INBOX_MESSAGES | InboxItem[] | New inbox messages. |
| NEW_INBOX_NOTIFICATION | InboxItem[] | New inbox notifications. |
| NOTIFICATIONS_ADDED | — | Badge/level notification queued. |
React Hook — useCaptainUp
The SDK provides a built-in React hook for reactive state management.
import { useCaptainUp } from 'captainup-react-native-sdk';
function GameProfile() {
const { user, isConnected, isAuthenticated, application } = useCaptainUp();
if (!isAuthenticated) return <Text>Not logged in</Text>;
return (
<View>
<Text>{user.name}</Text>
<Text>Level: {user.levelName}</Text>
<Text>Points: {user.currencies.points}</Text>
</View>
);
}With event callback (useful for toasts/logging):
const { user } = useCaptainUp({
onEvent: (event, data) => {
console.log('SDK event:', event, data);
},
});Returns:
| Property | Type | Description |
|----------|------|-------------|
| user | object \| null | User snapshot: userId, name, imageUrl, levelName, levelId, currencies, leaderboardPositions |
| isConnected | boolean | Whether the SDK is connected. |
| isAuthenticated | boolean | Whether a user is authenticated. |
| application | object \| null | Application data (badges, levels, assets, etc.). |
| syncState | () => void | Manually re-sync state from the SDK. |
The hook auto-subscribes to all SDK events and updates state reactively. Cleans up on unmount.
Exports
import CaptainUp, {
CaptainUpEvents,
ActionBuilder,
IntegrationUserBuilder,
ActionableEntityBuilder,
QueryBuilder,
LeaderboardTime,
AssetType,
useCaptainUp,
} from 'captainup-react-native-sdk';TypeScript
Full TypeScript declarations are included (index.d.ts).
Documentation
See the docs/ folder for the full HTML documentation.
License
MIT
