Skip to content

Instantly share code, notes, and snippets.

@rturk
Created July 8, 2020 16:38
Show Gist options
  • Save rturk/c9741b6a8aa0c18d549fe7775398ea29 to your computer and use it in GitHub Desktop.
Save rturk/c9741b6a8aa0c18d549fe7775398ea29 to your computer and use it in GitHub Desktop.
useCrisp - Load Crisp Chat with React App
import { useEffect, useRef } from 'react';
import { useScript } from './useScript';
//This will generate a new number every hour
//Crisp has a terrible CDN handeling process, this forces to load last version every hour
const getDateSeconds = () => {
const date = new Date();
const time = date.getTime();
return Math.floor(time / 3600000);
};
type UseCrisp = {
userRef: useCrisp_user;
crispId: string;
};
export const useCrisp = ({ userRef, crispId = process.env.CRISP_CHAT_ID }: UseCrisp) => {
const user = readInlineData(userCrispFragment, userRef);
useEffect(() => {
if (!user) {
return;
}
window.$crisp = [];
window.CRISP_WEBSITE_ID = crispId!;
window.CRISP_TOKEN_ID = `${user.company.id}-${user.id}`;
// window.$crisp.push(['safe', true]);
window.$crisp.push(['set', 'user:email', [user.email]]);
window.$crisp.push(['set', 'user:nickname', [user.name]]);
}, [user]);
//Force browser to always request for the backend a new file
const dateSeconds = useRef(getDateSeconds()).current;
const scriptURL = `https://client.crisp.chat/l.js?${dateSeconds}`;
const [loaded, error] = useScript(scriptURL);
useEffect(() => {
if (!error) {
return;
}
Sentry.captureException(new Error('Crisp not loaded'));
}, [error]);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment