Skip to content

Instantly share code, notes, and snippets.

@sravan-s
Created September 21, 2022 08:39
Show Gist options
  • Save sravan-s/44c83d4428915a56678d5ed76b3f0fff to your computer and use it in GitHub Desktop.
Save sravan-s/44c83d4428915a56678d5ed76b3f0fff to your computer and use it in GitHub Desktop.
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';
// 1 minute
const DEFAULT_SESSION_TOKEN_PERIOD = 1 * 60 * 1000;
// add your 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 => {
// curentUserInfo.accessToken = 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;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment