|
| 1 | +import {createHmac} from 'crypto'; |
| 2 | +import {useEffect, useState} from 'react'; |
| 3 | + |
| 4 | +import {useFrontChatBoot} from '../../lib/hooks/use-front-chat-boot'; |
| 5 | + |
| 6 | +/* |
| 7 | + * Constants. |
| 8 | + */ |
| 9 | + |
| 10 | +const chatId = '<CHAT_ID_REQUIRED>'; |
| 11 | + |
| 12 | +// Usually this will be an email for a verified user. |
| 13 | +const userId = '<USER_ID_REQUIRED>'; |
| 14 | + |
| 15 | +// This value is used to generate the user hash, and can be found in the Front channel settings. |
| 16 | +const identitySecret = '<IDENTITY_SECRET_REQUIRED>'; |
| 17 | + |
| 18 | +/* |
| 19 | + * User Hash. |
| 20 | + */ |
| 21 | + |
| 22 | +// This is a hash generated from the userId using the identity secret. |
| 23 | +// Follow the instructions here to generate the user hash: https://dev.frontapp.com/docs/identify-users#computing-the-user-hash |
| 24 | +// NOTE: This should only ever be generated server-side, and this is just an example. Do not generate this value client-side in your application. |
| 25 | +const hmac = createHmac('sha256', identitySecret); |
| 26 | +const userHash = hmac.update(userId).digest('hex'); |
| 27 | + |
| 28 | +/* |
| 29 | + * Component. |
| 30 | + */ |
| 31 | + |
| 32 | +function App() { |
| 33 | + const {frontChat, initialize, isInitialized} = useFrontChatBoot(document.body); |
| 34 | + |
| 35 | + const [isWindowVisible, setIsWindowVisible] = useState(false); |
| 36 | + |
| 37 | + // Example of using useFrontChat to initialize the chat widget when a component mounts. |
| 38 | + useEffect(() => { |
| 39 | + if (!initialize || isInitialized) { |
| 40 | + return; |
| 41 | + } |
| 42 | + |
| 43 | + // When initializing for a verified user, you must provide the `userId` and `userHash` options. |
| 44 | + initialize({chatId, userId, userHash}); |
| 45 | + }, [isInitialized, initialize, userHash]); |
| 46 | + |
| 47 | + // NOTE: You can also start the widget with the chat window visible by providing the `shouldShowWindow` |
| 48 | + // option to the 'init' command. The below effect is just an example of waiting for the chat widget to |
| 49 | + // be initialized, before performing another action. |
| 50 | + useEffect(() => { |
| 51 | + if (!frontChat || !isInitialized || isWindowVisible) { |
| 52 | + return; |
| 53 | + } |
| 54 | + |
| 55 | + frontChat('show'); |
| 56 | + setIsWindowVisible; |
| 57 | + }, [frontChat, isInitialized, isWindowVisible]); |
| 58 | + |
| 59 | + return <div>isInitialized: {isInitialized ? 'True' : 'False'}</div>; |
| 60 | +} |
0 commit comments