I have a chat feature in my app and very infrequently the chat box loads twice when reloading the page. Probably something do to with some weird react re-rendering. I would like for something to check if the script has been executed already and if so don't do it again.
Here is my relevant code
import { useEffect, useState, useRef } from 'react';
import { useDebouncedCallback } from 'use-debounce';
const debounceLoading = useDebouncedCallback((e) => {
const firstLoad = useRef(true);
loadScript();
setup();
}, 2000);
useEffect(() => {
if (firstLoad.current){
firstLoad.current = false;
return;
}
debounceLoading();
}, []);
useEffect(() => {
if (open) {
setWrapperClass('open');
setButtonIcon('/images/.svg');
} else {
setWrapperClass('closed');
setButtonIcon('/images/.svg');
}
}, [open]);
const loadScript = () => {...........}
return (
<div id="wrapper" className={wrapperClass}>
<div onClick={toggleChat} className="button">
<img src={buttonIcon} alt="Chat icon" />
Chat
</div>
<div id="box-container"></div>
</div>
);
}
I have looked at Verify External Script Is Loaded and https://medium.com/anna-coding/the-way-to-check-if-its-the-first-time-for-useeffect-function-is-being-run-in-react-hooks-170520554067. I also understand that this will not be a reproducible question and I'm well aware of that but any help would be appreciated.
My current code is giving me errors because the useRef hook can't be called inside a callback. Does anyone know the best way to fix my issue?