💫

Usage Examples

 

✨ Usage Examples


⚛️ React Integration

The ug-core SDK is vanilla JavaScript, making it easy to integrate into any framework. Here’s how it's used in the ChatAvatar.tsx React component.

The Core Concept: Decoupling

The SDK is intentionally decoupled from React. It manages all the complex state and logic internally. The React component's job is simply to:
  1. Instantiate the ConversationManager.
  1. Provide callback hooks to sync the SDK's internal state with the React component's state.
  1. Call high-level methods on the manager in response to user UI interactions (e.g., clicking a play button).

ChatAvatar.tsx

1. Instantiating the Manager
The ConversationManager is stored in a useRef to ensure it persists across component re-renders without triggering them.
// In ChatAvatar.tsx const conversationManagerRef = useRef<ConversationManager | null>(null); if (!conversationManagerRef.current) { // Configuration is created const convConfig: ConversationConfig = {/* ... config ... */ }; // Manager is instantiated conversationManagerRef.current = new ConversationManager(convConfig); }
2. Bridging State with React Hooks
The ConversationConfig's hooks property is the bridge between the SDK and the React UI. We pass setState functions from useState directly into these hooks.
// In ChatAvatar.tsx const [state, setState] = useState<ConversationState>(); const [subtitles, setSubtitles] = useState<any>(null); const [currentImage, setCurrentImage] = useState<string | null>(null); // ... inside the component const convConfig: f = { // ... other confighooks: { // When the SDK's state changes, it calls this hook... onStateChange: (newState: ConversationState) => { // ...which updates the React component's state, triggering a re-render.setState(newState); }, onSubtitleChange: (event: SubtitleChangeEvent) => { setSubtitles(event); }, onImageChange(event: ImageChangeEvent) { const imageData = `data:${event.format};base64,${event.image}`; setCurrentImage(imageData); }, onError: (error: ConversationError) => { toast.error(error.message); }, onAvatarAnimationChanged: ({ name, layer, loop }) => { // Forward the animation command to the Spine character component animatedCharacterRef.current?.setAnimation(layer, name, loop); }, }, };
3. Driving the SDK from the UI
User interactions, like clicking a button, call the simple, high-level methods on the ConversationManager instance.
// In ChatAvatar.tsx const handlePlayButtonClick = () => { if (isAudioPlaying) { conversationManagerRef.current?.pause(); } else { conversationManagerRef.current?.resume(); } }; const handleSendText = () => { if (textInput.trim()) { conversationManagerRef.current?.sendText(textInput); setTextInput(''); } };
This architecture provides a clean separation of concerns. The ug-core SDK handles the heavy lifting of conversation management, while the React component remains a lightweight view layer that simply reacts to data and events.