Перейти к основному содержимому

Клиентские библиотеки

Адаптеры фреймворков

Обёртка для React

Провайдер и два хука поверх SDK для TypeScript. Он устанавливает один клиент на страницу, поэтому строгий режим React не удваивает ваши события.

Где опубликован

@prodantix/react on npm. It wraps @prodantix/sdk, so install both.

Установка

Bash
bun add @prodantix/sdk @prodantix/react
ExportWhat it is
ProdantixProviderCreates the client once per page and provides it
useProdantixThe client for the page, or null
useMessengerA handle that opens and closes the widget, or null
prodantixConfigThe config when both key and host are present, else null
skipReasonWhy this mount will send nothing, or null
resetProdantixForTestClears the once-per-page install, for tests

Провайдер

Смонтируйте ProdantixProvider один раз, ближе к корню. Он создаёт веб-клиент при первом монтировании и дальше использует его повторно, потому что создание второго пропатчило бы History API дважды и удвоило каждое автоматически захваченное событие.

TypeScript
import { ProdantixProvider } from '@prodantix/react';

export const Providers = ({ children }: { children: ReactNode }) => (
  <ProdantixProvider
    options={{
      apiKey: process.env.NEXT_PUBLIC_PRODANTIX_KEY,
      host: 'https://eu.api.prodantix.com',
      messengerHost: 'https://eu.edge.prodantix.com',
    }}
  >
    {children}
  </ProdantixProvider>
);
Мессенджер появляется, только если вы передали messengerHost и проект включил его в консоли. Без конфигурации и без кеша не отрисовывается ничего, потому что кнопка по умолчанию была бы догадкой, нарисованной на странице клиента.

Хуки

useProdantix возвращает клиент страницы или null на сервере, до выполнения эффекта и вне провайдера. useMessenger возвращает дескриптор, открывающий и закрывающий виджет, и остаётся null, пока конфигурация проекта не прочитана и не сообщает, что он включён.

TypeScript
import { useMessenger, useProdantix } from '@prodantix/react';

export const HelpButton = () => {
  const prodantix = useProdantix();
  const messenger = useMessenger();

  // Both are null until the provider effect has run, so neither is assumed.
  return (
    <button
      onClick={() => {
        prodantix?.capture('help.opened');
        messenger?.open();
      }}
      type="button"
    >
      Get help
    </button>
  );
};

Когда он ничего не отправляет

Приложение выпускается точно так же с выключенным Prodantix, поэтому отсутствие ключа или хоста не ошибка. prodantixConfig сообщает, есть ли оба значения, а skipReason одной строкой говорит, почему монтирование ничего не отправит, вместо того чтобы молча вернуться.

TypeScript
import { prodantixConfig, skipReason } from '@prodantix/react';

const env = {
  host: process.env.NEXT_PUBLIC_PRODANTIX_HOST,
  key: process.env.NEXT_PUBLIC_PRODANTIX_KEY,
};

// null when either value is missing: the app runs with Prodantix switched off.
if (prodantixConfig(env) === null) {
  console.warn(skipReason(env, null));
}