UNPKG

@buddy-link/react

Version:

Buddy SDK - React components and hooks for wallet integration

73 lines (60 loc) 1.78 kB
"use client"; import { useState, useCallback } from 'react'; /** * Buddy SDK Hook Factory * @param {Object} config - Configuration options * @param {string} config.apiKey - App API key * @param {string} config.appId - Application ID * @param {string} [config.baseUrl] - Base URL for API calls * @returns {Object} Buddy SDK methods */ export function useBuddy(config) { const { apiKey, appId, baseUrl = '/api/v1' } = config; const [loading, setLoading] = useState(false); const [error, setError] = useState(null); /** * Execute an intent action * @param {string} action - The action to execute (from BUDDY_ACTIONS) * @param {Object} params - Action parameters * @returns {Promise<Object>} Action result */ const intent = useCallback(async (action, params = {}) => { if (!apiKey || !appId) { throw new Error('apiKey and appId are required for useBuddy'); } setLoading(true); setError(null); try { const response = await fetch(`${baseUrl}/intent`, { method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${apiKey}`, 'X-App-ID': appId }, body: JSON.stringify({ action, ...params }) }); if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`); } const result = await response.json(); if (!result.success) { throw new Error(result.error?.message || 'Intent execution failed'); } return result; } catch (err) { setError(err.message); throw err; } finally { setLoading(false); } }, [apiKey, appId, baseUrl]); return { intent, loading, error }; }