This version (v0.7) has not been published to npm yet.
Skip to content

React ​

@getenginex/sdk-react connects the core client and TanStack Query v5 to the React tree: reactive session, typed queries and mutations, invalidation after every write, cache cleanup on user switch and realtime. The package is client-only (the bundle starts with 'use client'). In Next.js, use @getenginex/sdk-next, which re-exports everything from here.

bash
npm i @getenginex/sdk @getenginex/sdk-react @tanstack/react-query

Peers: react >=18, @tanstack/react-query ^5 and @getenginex/sdk >=0.6.0 <1.0.0. In TypeScript, the app needs @types/react. If the tsconfig does not include the DOM lib, declare type VoidFunction = () => void in a .d.ts (it is the only DOM type that TanStack's .d.ts files use).

Provider ​

Create the core client once, outside the React tree, and pass it to EnginexProvider:

tsx
// main.tsx
import { createEnginexClient, localStorageTokenStore } from '@getenginex/sdk'
import { EnginexProvider } from '@getenginex/sdk-react'

const enginex = createEnginexClient({ locale: 'pt-BR', tokenStore: localStorageTokenStore() })

export function App() {
  return (
    <EnginexProvider client={enginex}>
      <Routes />
    </EnginexProvider>
  )
}

With the app's QueryClient ​

Without a queryClient, the provider creates one per instance (never a module singleton, so SSR does not share cache between requests), with a 60 s staleTime on queries. If the app already has a QueryClient, pass it: the provider uses it as-is, without changing any option, and the app keeps using TanStack's own useQueryClient.

tsx
import { QueryClient } from '@tanstack/react-query'

const queryClient = new QueryClient({
  defaultOptions: { queries: { staleTime: 5 * 60_000, retry: 1, refetchOnWindowFocus: false } },
})

<EnginexProvider client={enginex} queryClient={queryClient}>
  <Routes />
</EnginexProvider>

In your QueryClient, use a staleTime above zero: with TanStack's default (0), data hydrated from the server is fetched again as soon as it mounts (staleTime does not travel in the dehydrated state).

client and queryClient must be stable. To switch tenants, remount the provider (<EnginexProvider key={tenant} …>).

Session ​

tsx
import { useEnginex, useSession } from '@getenginex/sdk-react'

function Header() {
  const session = useSession()
  const enginex = useEnginex()
  if (session.status !== 'authenticated') return <LoginButton />
  return <button onClick={() => enginex.auth.logout()}>Log out</button>
}
  • useSession() uses useSyncExternalStore over client.session: the reference only changes when the session changes (refreshing the same user's tokens does not re-render).
  • On the server and during hydration it returns { status: 'anonymous' } and the real session appears right after, with no hydration error. If the server knows the session (cookie session, see Next.js), pass it as initialSession so the server and hydration render the same session in the part of the screen that depends only on it (header, menu).
  • User queries only after hydration: the factories build the key from the client's session (client.session), not from initialSession, and during SSR the browser client has no session. A component that renders a user query during SSR uses the 'anonymous' key and hydration fails. Gate those components on an authenticated useSession(), with the default (anonymous) initialSession, like the Header above; data hydrated from the server is used in the first render after hydration, with no request. Do not wrap components that render user queries during SSR with an authenticated initialSession; for player data in the HTML, use a Server Component (see Next.js).
  • useEnginex() returns the provider's client (throws outside it).

User keys: useUserKey ​

To invalidate or read the signed-in player's data from the cache, useUserKey(namespace?, method?) returns the ['enginex', 'user', userId, namespace?, method?] prefix for the current session, or null with no session:

tsx
import { useUserKey } from '@getenginex/sdk-react'
import { useQueryClient } from '@tanstack/react-query'

function RefreshWallet() {
  const queryClient = useQueryClient()
  const walletKey = useUserKey('wallet') // ['enginex', 'user', userId, 'wallet']
  return (
    <button disabled={!walletKey} onClick={() => walletKey && queryClient.invalidateQueries({ queryKey: walletKey })}>
      Refresh
    </button>
  )
}

Outside a component, enginexKeys.user(userId, namespace, method?) (from @getenginex/sdk/query) builds the same key. The layout is a contract and the array is frozen. For an exact setQueryData, use the key from the factory itself (q.wallet.getBalance().queryKey).

User switch ​

When the session's user changes (logout, login, or login with a different sub), the provider removes from the cache everything under ['enginex', 'user']: one player's data is never served to another. ['enginex', 'public'] and the app's keys are left as they are. If the app has its own keys with player data, clear them yourself (e.g. with useSession in an effect, or in your store's subscribe).

Queries ​

tsx
import { useEnginexQueries, useEnginexQuery } from '@getenginex/sdk-react'

function Balance() {
  const q = useEnginexQueries()
  const balance = useEnginexQuery(q.wallet.getBalance(), { refetchInterval: 10_000 })
  if (balance.isPending) return <Skeleton />
  if (balance.error) return <ErrorMessage code={balance.error.code} />
  return <p>{balance.data.realBalance}</p>
}
  • useEnginexQueries() returns the core factories, memoized per client. Call the factory on every render (q.wallet.getBalance() inside the component), without storing the result: the key carries the userId at call time, and the hooks re-render when the session changes identity, so the new key comes on its own.
  • Products: useEnginexQueries(createIgamingQueries, igaming) (or createPredictionsQueries) returns the product package's factories, memoized per factory and product.
  • overrides (refetchInterval, select, enabled, staleTime, retry...) win over the factory's options; queryKey and queryFn cannot be replaced. error is typed as EnginexError.
  • Cancellation: unmounting the last component that observes the query aborts the fetch and raises no error.
  • Retry: UNAUTHENTICATED (user query with no session) is not retried, because it made no request; the other errors follow the QueryClient's retry (or overrides.retry).
tsx
import { createIgaming } from '@getenginex/sdk-igaming'
import { createIgamingQueries } from '@getenginex/sdk-igaming/query'

const igaming = createIgaming(enginex) // in the same module as the client, once

function Lobby() {
  const ig = useEnginexQueries(createIgamingQueries, igaming)
  const games = useEnginexQuery(ig.casino.listGames({ page: 1 }), { select: (page) => page.items })
  return <GameGrid games={games.data ?? []} />
}

Mutations ​

tsx
import { useEnginexMutation, useEnginexMutations } from '@getenginex/sdk-react'

function DepositButton() {
  const m = useEnginexMutations()
  const pix = useEnginexMutation(m.deposits.createPix(), {
    onSuccess: (deposit) => router.push(`/deposit/${deposit.id}`),
    onError: (error) => toast(error.code),
  })
  return (
    <button disabled={pix.isPending} onClick={() => pix.mutate({ amount: 5000 })}>
      Deposit
    </button>
  )
}
  • On success, it invalidates exactly invalidates(input, result) (here: balance, transactions and deposits), waits for the refetches and only then calls your onSuccess: mutateAsync and isPending finish with the data already updated. If an active query is refetching with retries, isPending lasts until it finishes.
  • On error it invalidates nothing and onError receives the EnginexError. If your own onSuccess throws, the invalidation has already happened and onError receives its error (which is not necessarily an EnginexError).
  • useEnginexMutations(createIgamingMutations, igaming) returns a product's mutations.

Idempotency in mutations ​

Deposit, withdrawal (request, confirmOtp), bonus.optIn/claim/redeemPromoCode, loyalty.redeem and the Predictions orders send an Idempotency-Key. The full rule (table of ambiguous failures, ABORTED, explicit key) is in Idempotency; in React:

  • The attempt lives in the hook instance. useEnginexMutation keeps the attempt (input and key) per instance and it survives re-renders and TanStack's retry, even if m.deposits.createPix() returns new options on every render. Two hook instances never share a key, and neither does the same instance when it switches method (e.g. deposit ↔ withdrawal with the same input).
  • Adjustments go in the second argument. Pass retry, onSuccess etc. in overrides: useEnginexMutation(m.deposits.createPix(), { retry: 1 }). Spreading the options (useEnginexMutation({ ...m.deposits.createPix(), retry: 1 })) loses the SDK's call, which the spread does not copy, and with it the per-instance attempt: the key no longer survives a re-render.
  • Only after an ambiguous failure. NETWORK_ERROR, TIMEOUT, 5xx, KEY_IN_USE (the first attempt is still being processed) and VALIDATION_ERROR after a 2xx (the operation already happened) keep the key. Success, the other 4xx and ABORTED discard it: the next mutate is a new operation.
  • The input is compared by content. A "try again" with a literal pix.mutate({ amount: 5000 }), after a 503, reuses the key: you do not need to keep the object. Changing the amount starts a new operation. After success, the same amount again (a quick-deposit button) is also a new operation.
  • confirmOtp: pass the requestId from withdrawals.request (mutate({ otp, requestId })); a new challenge never reuses the previous one's key. The requestId does not go to the gateway.
  • Explicit key: m.deposits.createPix({ idempotencyKey }) wins over the attempt, so you can store the key and repeat after reloading the page (or after an ABORTED). Generate one per operation (when the player confirms), never one per screen. The key is read when the factory is called and enters the options of the render, so mutate must run after the render that received it (in the same handler that stores the key in state, the mutation still has the old options). A two-step flow solves it:
tsx
const [operation, setOperation] = useState<{ amount: number; idempotencyKey: string }>()
const pix = useEnginexMutation(m.deposits.createPix({ idempotencyKey: operation?.idempotencyKey }))

// step 1: the player confirms the amount (one key per operation)
const confirm = (amount: number) => setOperation({ amount, idempotencyKey: crypto.randomUUID() })
// step 2, on another click (the key is already in the options); "try again" calls pay() once more
const pay = () => operation && pix.mutate({ amount: operation.amount })

When in doubt, prefer the simple path: without an explicit key, the SDK takes care of it.

  • Batch orders: orders.placeBatch sends one key per order (in the body) and reuses it, per result of createPredictionsMutations (memoized by useEnginexMutations), as long as the batch's content is the same and it has not succeeded (ambiguous failure or partial success). Full success, an unambiguous error or different content produce new keys. The batch has no mutation symbol: the attempt lives in that result, shared by every orders.placeBatch() call on it (two components with the same batch after an ambiguous failure use the same keys).

Realtime ​

tsx
import { coreTopics } from '@getenginex/sdk/realtime'
import { useRealtime, useRealtimeStatus, useRealtimeSync } from '@getenginex/sdk-react'

function Shell({ children }: { children: React.ReactNode }) {
  useRealtimeSync() // balance and notifications in the cache, no polling
  const status = useRealtimeStatus()
  return (
    <>
      {status === 'reconnecting' && <Banner>Reconnecting...</Banner>}
      {children}
    </>
  )
}

function NotificationToasts() {
  useRealtime(coreTopics.notification(), (n) => toast(n.title))
  return null
}
  • useRealtime(topic, handler) subscribes on mount and unsubscribes on unmount: a single subscription in StrictMode, the latest handler receives the messages without resubscribing, the topic is compared by key (coreTopics.balance() on every render does not resubscribe) and null does not subscribe. A private topic is only subscribed with a user in the session and resubscribes on user switch.
  • useRealtimeStatus() returns 'connecting' | 'open' | 'reconnecting' | 'closed' | 'unavailable' ('closed' on the server). It does not open the connection.
  • useRealtimeSync() is opt-in. With a user in the session, it invalidates the balance query on every balance_update (it never uses setQueryData: the message does not carry reserved and bonus amounts), the notifications queries on every notification and, after a reconnection (onResync), the wallet and notifications queries. Only active queries are refetched.

Product topics go in topics, each with the keys it feeds. Build the keys with the factories (.queryKey), never by hand; use the function form for user keys, which depend on the session at the time of the message:

tsx
import { createPredictionsQueries } from '@getenginex/sdk-predictions/query'
import { predictionsTopics } from '@getenginex/sdk-predictions/realtime'

function MarketSync({ marketId }: { marketId: string }) {
  const pq = useEnginexQueries(createPredictionsQueries, predictions)
  useRealtimeSync({
    topics: [
      {
        topic: predictionsTopics.orderbook({ marketId }),
        invalidate: [pq.markets.getOrderbook({ marketId }).queryKey],
      },
      {
        topic: predictionsTopics.orders(),
        invalidate: () => [pq.orders.list().queryKey],
      },
    ],
  })
  return null
}

useRealtimeSync does not apply the messages' content to the cache: for that (e.g. applying orderbook deltas), use useRealtime. The WebSocket URL and the rest of the connection follow the core's Realtime (wsUrl in createEnginexClient).

Session from an app store ​

If the app already keeps tokens in a store (zustand, Redux), do not duplicate them: implement a TokenStore on top of it and pass it to the client. The SDK reads, writes and subscribes to the store; the rest of the app keeps using the store as before. An example with zustand and persist (the players' format):

ts
// lib/enginex.ts
import { createEnginexClient, type TokenStore } from '@getenginex/sdk'
import { useAuthStore } from '@/stores/auth' // create(persist(...)) with accessToken/refreshToken

const zustandTokenStore: TokenStore = {
  get() {
    const { accessToken, refreshToken } = useAuthStore.getState()
    return accessToken && refreshToken ? { accessToken, refreshToken } : null
  },
  set({ accessToken, refreshToken }) {
    useAuthStore.setState({ accessToken, refreshToken, isAuthenticated: true })
  },
  clear() {
    useAuthStore.getState().logout()
  },
  subscribe(listener) {
    // Only the tokens matter: changes to other store fields do not notify the SDK.
    return useAuthStore.subscribe((state, prev) => {
      if (state.accessToken !== prev.accessToken || state.refreshToken !== prev.refreshToken) listener()
    })
  },
}

export const enginex = createEnginexClient({ locale: 'pt-BR', tokenStore: zustandTokenStore })
  • get() must be synchronous and cheap. zustand's persist with localStorage rehydrates synchronously when the store is created; with an asynchronous storage, the SDK sees "no session" until rehydration finishes and is then notified by subscribe.
  • The SDK compares tokens by content, so returning a new object on every get() does not cause a re-render.
  • Other tabs: persist does not sync tabs on its own. If the app needs it, call useAuthStore.persist.rehydrate() in a storage event listener (the subscribe above notifies the SDK).
  • A login done by the SDK (enginex.auth.login) writes the tokens with set; user data the app keeps in the same store (name, email) remains the app's responsibility.

Testing ​

The core mocks (createMockFetch and createMockRealtime, from @getenginex/sdk/testing; see Testing and mocks) work with @testing-library/react in a DOM environment (happy-dom or jsdom): render the component inside an EnginexProvider with a fake client.

tsx
import { createEnginexClient, memoryTokenStore } from '@getenginex/sdk'
import { createMockFetch, createMockRealtime } from '@getenginex/sdk/testing'
import { EnginexProvider } from '@getenginex/sdk-react'
import { QueryClient } from '@tanstack/react-query'
import { render, screen } from '@testing-library/react'
import { expect, it } from 'vitest'
import { Balance } from './Balance'

it('shows the player balance', async () => {
  const realtime = createMockRealtime()
  const enginex = createEnginexClient({
    baseUrl: 'https://gateway.test',
    tenantHost: 'casino.test',
    tokenStore: memoryTokenStore(),
    fetch: createMockFetch(),
    webSocket: realtime.webSocket,
  })
  await enginex.auth.login({ email: 'ana@exemplo.com', password: 'Senha@123' })

  // One QueryClient per test, without retries: an error shows up at once.
  const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
  render(
    <EnginexProvider client={enginex} queryClient={queryClient}>
      <Balance />
    </EnginexProvider>,
  )

  expect(await screen.findByText(/R\$/)).toBeTruthy()
})

To test a hook of your own, use renderHook with the provider as the wrapper:

tsx
import { EnginexProvider, useEnginexQueries, useEnginexQuery } from '@getenginex/sdk-react'
import { QueryClient } from '@tanstack/react-query'
import { renderHook, waitFor } from '@testing-library/react'
import type { ReactNode } from 'react'
import { expect } from 'vitest'

const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
const wrapper = ({ children }: { children: ReactNode }) => (
  <EnginexProvider client={enginex} queryClient={queryClient}>
    {children}
  </EnginexProvider>
)

const { result } = renderHook(() => useEnginexQuery(useEnginexQueries().wallet.getBalance()), { wrapper })
await waitFor(() => expect(result.current.isSuccess).toBe(true))
  • Create the client and the QueryClient per test: the cache and the mock's state (balance, deposits, session) never leak between tests.
  • For product screens, add the product routes to the mock: createMockFetch(withIgamingRoutes()) or withPredictionsRoutes() (see Testing and mocks).
  • To simulate an error, override a route: createMockFetch({ routes: { 'GET /api/v1/wallet/balance': () => fail(503, 'UNAVAILABLE') } }).
  • With createMockRealtime, realtime.emit(...) pushes a message to useRealtime and useRealtimeSync; emit only after the component has mounted and subscribed (realtime.sent() lists the subscribe frames).