Skip to content

Instantly share code, notes, and snippets.

@rturk
Created July 8, 2020 16:38
Show Gist options
  • Select an option

  • Save rturk/c9741b6a8aa0c18d549fe7775398ea29 to your computer and use it in GitHub Desktop.

Select an option

Save rturk/c9741b6a8aa0c18d549fe7775398ea29 to your computer and use it in GitHub Desktop.

Revisions

  1. rturk created this gist Jul 8, 2020.
    47 changes: 47 additions & 0 deletions useCrisp.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,47 @@
    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]);
    };