Skip to content

Instantly share code, notes, and snippets.

@coliveravenegas
Created October 20, 2021 14:19
Show Gist options
  • Save coliveravenegas/ae4cafdf29cc5d83fc45fb437a921048 to your computer and use it in GitHub Desktop.
Save coliveravenegas/ae4cafdf29cc5d83fc45fb437a921048 to your computer and use it in GitHub Desktop.
import React, { useEffect, useState } from 'react';
import { Loader } from '@crehana/ui';
import { useStickyState } from '@crehana/react-hooks';
import Loadable from 'Jsx/Shared/Loadable';
const LANDING_USER_ARRIVALS_REQUIRED_TO_TRIGGER = 2;
type CallCenterDialogLazy = {
secondsToTrigger: number;
identifier?: string;
configurations: 'only-timer' | 'all';
};
const CallCenterDialogLazy = ({
secondsToTrigger = 0,
identifier = 'generic-dialog',
configuration = 'all',
}) => {
const [isOpen, setIsOpen] = useState(false);
const [evaluatingConfiguration, setEvaluatingConfiguration] =
useState<'time' | 'visit' | ''>('');
const dialogIdentifier = identifier;
const [pageVisitCounter, setPageVisitCounter] = useStickyState(
0,
`PAGE_VISIT_COUNTER_${dialogIdentifier}`,
);
// This store if the user has previously closed the dialog by any reason
const [closedByTime, setClosedByTime] = useStickyState(
false,
`closedByTime_${dialogIdentifier}`,
);
const [closedByVisit, setClosedByVisit] = useStickyState(
false,
`closedByVisit_${dialogIdentifier}`,
);
const startTriggerByTime = () => {
setEvaluatingConfiguration('time');
setTimeout(() => {
setIsOpen(true);
}, secondsToTrigger * 1000);
};
const startTriggerByVisit = () => {
setEvaluatingConfiguration('visit');
// We are using a +1 hack 'cause the pageVisitCounter doesn't include the current visit
if (pageVisitCounter + 1 === LANDING_USER_ARRIVALS_REQUIRED_TO_TRIGGER) {
setIsOpen(true);
} else {
// Increase the page visit counter
setPageVisitCounter(pageVisitCounter + 1);
}
};
useEffect(() => {
if (configuration === 'only-timer' && !closedByTime) {
startTriggerByTime();
} else if (configuration === 'all') {
/* eslint-disable no-lonely-if */
if (!closedByTime) {
startTriggerByTime();
} else if (!closedByVisit) {
startTriggerByVisit();
}
}
}, []);
return (
<Loadable
module={() =>
import(
/* webpackChunkName: "MembershipPage-CallCenterDialog" */
'./CallCenterDialog'
)
}
Loader={<Loader size={36} />}
isOpen={isOpen}
closeDialog={() => {
setIsOpen(false);
// Set closedBy
if (evaluatingConfiguration === 'time') {
setClosedByTime(true);
} else {
setClosedByVisit(true);
}
}}
/>
);
};
export default CallCenterDialogLazy;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment