Skip to content

Instantly share code, notes, and snippets.

@DaniloOliveira28
Last active April 12, 2024 08:01
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save DaniloOliveira28/8a8fa7587a68fb259dfe428bf637640c to your computer and use it in GitHub Desktop.
Save DaniloOliveira28/8a8fa7587a68fb259dfe428bf637640c to your computer and use it in GitHub Desktop.
Hook to manage the hubspot conversations chat using relay as global store
import { useState } from 'react';
import { useCommitLocalUpdate } from '../../components/utils/relay';
function loadOrRefreshChat(opened: boolean) {
if (window.HubSpotConversations.widget.status().loaded === true) {
window.HubSpotConversations.widget.refresh();
} else {
window.HubSpotConversations.widget.load({ widgetOpen: opened });
}
}
export const useLiveChatExternalApi = () => {
const [hsChatLoaded, setHsChatLoaded] = useState(false);
const { commit: createOrUpdate } = useCommitLocalUpdate((store, data) => {
// initialize local store
const fieldKey = 'settings';
const __typename = 'Settings';
const dataID = `client:${__typename}`;
const checkRecord = store.get(dataID);
if (!checkRecord) {
const newRecord = store.create(dataID, __typename);
newRecord.setValue(data.isHsLoaded, 'isHubspotChatLoaded');
store.getRoot().setLinkedRecord(newRecord, fieldKey);
} else {
const record = store.getRoot().getLinkedRecord('settings');
record.setValue(data.isHsLoaded, 'isHubspotChatLoaded');
}
});
const loadChat = (opened: boolean, email?: string | null) => {
setHsChatLoaded(true);
if (email) {
const _hsq = (window._hsq = window._hsq || []);
_hsq.push([
'identify',
{
email: email,
api: 'True',
},
]); //Identify User
_hsq.push([
'trackEvent',
{
id: 'User asked for Support',
},
]); //Track Event
}
loadOrRefreshChat(opened);
createOrUpdate({
isHsLoaded: true,
});
};
const removeChat = () => {
const isApiPresent = window.HubSpotConversations && window.HubSpotConversations.widget;
if (isApiPresent) {
window.HubSpotConversations.widget.remove();
setHsChatLoaded(false);
createOrUpdate({
isHsLoaded: false,
});
}
};
const isChatLoaded = () =>
window.HubSpotConversations &&
window.HubSpotConversations.widget &&
window.HubSpotConversations.widget.status().loaded;
return { loadChat, removeChat, isChatLoaded, hsChatLoaded };
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment