UIKit React v3
UIKit React
UIKit
React
Home
/
UIKit
/
React
This is the new Docs for UIKit v3 for React. To see the previous Docs, click here.

Handlers

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

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

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

GroupChannelHandler

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

OpenChannelHandler

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

UserEventHandler

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

Session handlers

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) => {
        console.log('SessionHandler.onSessionTokenRequired()');
        issueSessionToken(appInfo)
        .then(token => {
            // When using access token, set `curentUserInfo.accessToken` to `token`.
            resolve(token);
        })
        .catch(err => reject(err));
    };
    sessionHandler.onSessionRefreshed = () => {
        console.log('SessionHandler.onSessionRefreshed()');
    };
    sessionHandler.onSessionError = (err) => {
        console.log('SessionHandler.onSessionError()', err);
    };
    sessionHandler.onSessionClosed = () => {
        console.log('SessionHandler.onSessionClosed()');
    };

    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 intiateSession = async () => {
                const token = await issueSessionToken(appInfo);
                setTkn(token);
            };
            intiateSession();
        }
    }, [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;