Chat UIKit React v3
Chat UIKit React
Chat UIKit
React
Version 3

Handlers

Copy link

Sendbird UIKit for React provides various handlers such as channel event handlers and session handlers to manage activities and events that occur in the client app. See the guides below on how to install and use them.


Channel event handlers

Copy link

Due to a version update from v3 to v4 in the Chat SDK, UIKit implemented custom channel event handlers that you can import instead of calling the channel handler from sdkInstance. See the following codes on how to add the UIKit channel event handlers.

ConnectionHandler

Copy link
import ConnectionHandler from "@sendbird/uikit-react/handlers/ConnectionHandler";

Sendbird UIKit provides a ConnectionHandler, an event handler used by the SDK to manage connection events such as reconnection attempts and failures. This handler is especially useful in scenarios where network conditions are unstable or when the user switches between different network types (e.g., Wi-Fi to cellular). It is also beneficial when you want to implement custom logic or update the UI in response to these connection events.

Below is an example of how to use the ConnectionHandler in UIKit:

import React, { useEffect } from "react";

import SendbirdProvider from "@sendbird/uikit-react/SendbirdProvider";
import useSendbirdStateContext from "@sendbird/uikit-react/useSendbirdStateContext";
import ConnectionHandler from "@sendbird/uikit-react/handlers/ConnectionHandler";

const CustomConnectionHandler = () => {
  const store = useSendbirdStateContext();
  const sdk = store?.stores?.sdkStore?.sdk;

  useEffect(() => {
    try {
      const handler = new ConnectionHandler({
        onDisconnected() {
          console.log("onDisconnected");
          // Optionally, update UI to inform the user
        },
        onReconnectStarted() {
          console.log("onReconnectStarted");
          // Optionally, update UI to inform the user
        },
        onReconnectSucceeded() {
          console.log("onReconnectSucceeded");
          // Optionally, update UI to inform the user
        },
        onReconnectFailed() {
          console.log("onReconnectFailed");
          // Optionally, update UI to inform the user
        },
      });

      if (typeof sdk?.addConnectionHandler === "function") {
        sdk.addConnectionHandler("UNIQUE_HANDLER_ID", handler);
      }
    } catch {
      console.error("Something went wrong with the connectionHandler registration");
    }

    // Clean up the connection handler when the component unmounts
    return () => {
      try {
        sdk.removeConnectionHandler("UNIQUE_HANDLER_ID");
      } catch {
        console.error("Failed to remove the connectionHandler");
      }
    };
  }, [sdk]);

  return null;
};

export default function App() {
  return (
    <SendbirdProvider
        appId="YOUR_APP_ID"
        userId="YOUR_USER_ID"
      >
      <CustomConnectionHandler />
      {/* Other components can be added here */}
    </SendbirdProvider>
  );
}

GroupChannelHandler

Copy link
import GroupChannelHandler from "@sendbird/uikit-react/handlers/GroupChannelHandler";

OpenChannelHandler

Copy link
import OpenChannelHandler from "@sendbird/uikit-react/handlers/OpenChannelHandler";

UserEventHandler

Copy link
import UserEventHandler from "@sendbird/uikit-react/handlers/UserEventHandler";

Session handlers

Copy link

Sendbird UIKit provides a session handler, which is an event handler that the SDK uses to renew a session token. To securely authenticate a user, you can require an authentication token in the form of either an access token or a session token. Each user has an access token that can be passed to the client app and authenticated by the server. To learn more about how to connect to the Sendbird server with a user ID and a token, see Authentication in Chat SDK for JavaScript.

If a user is authenticated with a session token, the Chat SDK connects the user to the Sendbird server and can send data requests to it for ten minutes as long as the session token hasn't expired or hasn't been revoked. Upon the user's session expiration, the Chat SDK will refresh the session internally. However, if the session token has expired or has been revoked, the Chat SDK can't do so. In that case, the client app needs to implement a session handler to refresh the token and pass it back to the SDK so that it can refresh the session again. Refer to the code below on how to use the session handler in UIKit.

import { useEffect, useState } from 'react';
import SendbirdProvider from '@sendbird/uikit-react/SendbirdProvider';
import SessionHandler from '@sendbird/uikit-react/handlers/SessionHandler';
import ChannelList from '@sendbird/uikit-react/ChannelList';
import Channel from '@sendbird/uikit-react/Channel';

import '@sendbird/uikit-react/dist/index.css';

// Set default session token expiration period to 1 minute.
const DEFAULT_SESSION_TOKEN_PERIOD = 1 * 60 * 1000;

// Add client app info.
const appInfo = {
    appId: 'xxx',
    apiHost: 'xxx',
    apiToken: 'xxx',
    userId: 'xxx',
};

const configureSession = (sdk) => {
  const sessionHandler = new SessionHandler();
  sessionHandler.onSessionTokenRequired = (resolve, reject) => {
    // A new session token is required in the SDK to refresh the session.
    // Refresh the session token and pass it onto the SDK through resolve(NEW_TOKEN).
    // If you don't want to refresh the session, pass on a null value through resolve(null).
    // If any error occurs while refreshing the token, let the SDK know about it through reject(error).
    console.log('SessionHandler.onSessionTokenRequired()');
    issueSessionToken(appInfo)
    .then(token => {
      // When using access token, set `currentUserInfo.accessToken` to `token`.
      resolve(token);
    })
    .catch(err => reject(err));
  };
  sessionHandler.onSessionClosed = () => {
    // The session refresh has been denied from the app.
    // The client app should guide the user to a login page to log in again.
    console.log('SessionHandler.onSessionClosed()');
  };
  sessionHandler.onSessionRefreshed = () => {
    // OPTIONAL. No action is required.
    // This is called when the session is refreshed.
    console.log('SessionHandler.onSessionRefreshed()');
  };
  sessionHandler.onSessionError = (err) => {
    // OPTIONAL. No action is required.
    // This is called when an error occurs during the session refresh.
    console.log('SessionHandler.onSessionError()', err);
  };
  return sessionHandler;
}

const issueSessionToken = async (appInfo) => {
    const period = DEFAULT_SESSION_TOKEN_PERIOD;
    const endpoint = `${appInfo.apiHost}/v3/users/${appInfo.userId}/token`;
    const response = await fetch(endpoint, {
        method: 'POST',
        headers: {
            'Api-Token': appInfo.apiToken,
            'Content-Type': 'application/json; charset=utf-8'
        },
        body: JSON.stringify({
            expires_at: Date.now() + period,
        }),
    });
    const result = await response.json();
    return (result.token);
};

function App() {
    const [tkn, setTkn] = useState(false);
    useEffect(() => {
        if (!tkn) {
            console.warn('inside')
            const initiateSession = async () => {
                const token = await issueSessionToken(appInfo);
                setTkn(token);
            };
            initiateSession();
        }
    }, [tkn])
    const [currentChannelUrl, setCurrentChannelUrl] = useState("");

    if (!tkn) {
        return 'no tkn';
    }
    return (
        <SendbirdProvider
            allowProfileEdit
            appId={appInfo.appId}
            userId={appInfo?.userId}
            accessToken={tkn}
            configureSession={configureSession}
        >
            <ChannelList
                onChannelSelect={(channel) => {
                    if (channel && channel.url) {
                        setCurrentChannelUrl(channel.url);
                    }
                }}
            />
            <Channel channelUrl={currentChannelUrl} />
        </SendbirdProvider>
    );
}

export default App;