Skip to content

Instantly share code, notes, and snippets.

@sravan-s
Last active September 16, 2022 11:06
Show Gist options
  • Save sravan-s/4bfd6379c8561112a0fcd0bc3f1b7d15 to your computer and use it in GitHub Desktop.
Save sravan-s/4bfd6379c8561112a0fcd0bc3f1b7d15 to your computer and use it in GitHub Desktop.
Sample for connection
import { useState, useEffect } from 'react';
import SendbirdChat, { SessionHandler } from '@sendbird/chat';
import {
GroupChannelModule,
} from '@sendbird/chat/groupChannel';
// 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(() => {
// fetches token the first time
if (!tkn) {
const intiateSession = async () => {
const token = await issueSessionToken(appInfo);
setTkn(token);
};
intiateSession();
}
}, [tkn]);
if (!tkn) {
return 'no token';
}
return (
<div className="App">
<SendbirdProvider
appId={appInfo.appId}
userId={appInfo.userId}
accessToken={tkn}
configureSession={configureSession}
/>
</div>
);
}
export default App;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment