@vegacap/react
v0.1.0
Published
React hooks for the VegaCap Platform API — useSession, useCreateSession, useEmbed
Downloads
25
Maintainers
Readme
@vegacap/react
React hooks for the VegaCap Platform API. Thin wrapper over fetch + @vegacap/sdk — no React Query dependency, no Node runtime, works in any bundler.
npm install @vegacap/react @vegacap/sdkPeer dep: react >= 18.
Quickstart
Wrap your app in <VegaCapProvider> and point baseUrl at your own server-side proxy (BFF). Never ship a secret key (vegacap_sk_*) to the browser.
import { VegaCapProvider } from '@vegacap/react';
export default function App() {
return (
<VegaCapProvider
publishableKey="vegacap_pk_live_..."
baseUrl="/api/vegacap"
>
<MyApp />
</VegaCapProvider>
);
}Then use the hooks anywhere in the tree:
import { useCreateSession, useEmbed } from '@vegacap/react';
function StartAssessment() {
const { createSession, isLoading } = useCreateSession();
const [token, setToken] = useState<string | null>(null);
const start = async () => {
const session = await createSession({
assessmentType: 'disc',
candidate: { externalId: 'user-123', name: 'Jane' },
});
setToken(session.sessionToken);
};
return token
? <AssessmentEmbed token={token} />
: <button onClick={start} disabled={isLoading}>Start DiSC</button>;
}
function AssessmentEmbed({ token }: { token: string }) {
const { container, state } = useEmbed({
sessionToken: token,
onComplete: (r) => console.log('done', r),
});
return (
<div>
<div ref={container} />
<p>{state}</p>
</div>
);
}BFF (backend-for-frontend) pattern
The REST API only accepts secret keys (vegacap_sk_*). Those keys grant full access to your organization, so they must stay on your server.
The recommended pattern is a thin proxy. For Next.js App Router:
// app/api/vegacap/[...path]/route.ts
import { NextRequest } from 'next/server';
const UPSTREAM = 'https://vegacapltd.com/api/v1';
async function proxy(req: NextRequest, { params }: { params: Promise<{ path: string[] }> }) {
const { path } = await params;
const url = `${UPSTREAM}/${path.join('/')}${req.nextUrl.search}`;
const body = req.body ? await req.text() : undefined;
const res = await fetch(url, {
method: req.method,
headers: {
'Authorization': `Bearer ${process.env.VEGACAP_SECRET_KEY!}`,
'Content-Type': req.headers.get('content-type') ?? 'application/json',
},
body,
});
return new Response(await res.text(), {
status: res.status,
headers: { 'Content-Type': res.headers.get('content-type') ?? 'application/json' },
});
}
export { proxy as GET, proxy as POST, proxy as PATCH, proxy as DELETE };Add your own auth + rate limiting in the proxy before hitting the upstream.
Hooks reference
useSession(sessionId)
Fetches a single session by id. Re-runs when sessionId changes.
const { data, isLoading, error, refetch } = useSession('sess_abc123');Returns { data: SessionResult | null, isLoading, error, refetch }.
useCreateSession()
Mutation hook. Returns a createSession(params) function.
const { createSession, isLoading, error, data, reset } = useCreateSession();createSession resolves with a Session (including sessionToken) or throws a VegaCapReactError.
useSessionsList(filters?)
Paginated list.
const { data } = useSessionsList({ status: 'completed', limit: 20, offset: 0 });Pass a new offset to paginate. The hook stringifies filters internally, so object literals are fine as long as the values are primitives.
useEmbed({ sessionToken, onComplete, onError, theme? })
Mounts the embed SDK iframe into a container ref.
const { container, state, error } = useEmbed({
sessionToken,
onReady: () => console.log('ready'),
onComplete: (e) => console.log('done', e),
});
return <div ref={container} />;state transitions: idle → loading → ready → started → completed | error.
SSR / Next.js notes
useEmbedonly mounts insideuseEffect, so it is safe in server-rendered layouts. The<div ref={container} />renders on the server as an empty div.VegaCapProvideritself is a client component — mark your wrapping component with'use client'or import it from a client layout.fetchis polyfilled in Next.js server runtime, but these hooks only callfetchfrom the client, so SSR paths do not hit the network.- When using React 18 StrictMode,
useEmbedguards against double-mounting via adata-vegacap-mountedattribute on the container.
Error handling
Failed requests throw VegaCapReactError:
import { VegaCapReactError } from '@vegacap/react';
try {
await createSession({ ... });
} catch (err) {
if (err instanceof VegaCapReactError) {
console.log(err.code, err.statusCode, err.docUrl);
}
}License
MIT
