Обёртка для React
Провайдер и два хука поверх SDK для TypeScript. Он устанавливает один клиент на страницу, поэтому строгий режим React не удваивает ваши события.
Где опубликован
@prodantix/react on npm. It wraps @prodantix/sdk, so install both.
Установка
bun add @prodantix/sdk @prodantix/react| Export | What it is |
|---|---|
| ProdantixProvider | Creates the client once per page and provides it |
| useProdantix | The client for the page, or null |
| useMessenger | A handle that opens and closes the widget, or null |
| prodantixConfig | The config when both key and host are present, else null |
| skipReason | Why this mount will send nothing, or null |
| resetProdantixForTest | Clears the once-per-page install, for tests |
Провайдер
Смонтируйте ProdantixProvider один раз, ближе к корню. Он создаёт веб-клиент при первом монтировании и дальше использует его повторно, потому что создание второго пропатчило бы History API дважды и удвоило каждое автоматически захваченное событие.
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>
);Хуки
useProdantix возвращает клиент страницы или null на сервере, до выполнения эффекта и вне провайдера. useMessenger возвращает дескриптор, открывающий и закрывающий виджет, и остаётся null, пока конфигурация проекта не прочитана и не сообщает, что он включён.
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 одной строкой говорит, почему монтирование ничего не отправит, вместо того чтобы молча вернуться.
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));
}