ShogoTGM
ShogoTGM

Reputation: 498

React.js: How to call function only once watching scroll position

I would like to add value to window Object(google tag manager's dataLayer) when certain component is viewable on screen. Then, need to handle calling function not to be multiple.

So, I tried to write code like below...

import _ from 'lodash';

export const ContentsComponent = () => {
  const DEFAULT_SCROLL_POSITION = 0;

  const [isPushed, setIsPushed] = useState<boolean>(false);

  const setScroll = (event: Event) => {
    const newScroll = (event.target as Document).documentElement.scrollTop;
    if ((newScroll > 400) && !isPushed) {
      setIsPushed(true);
      justOneceFunction()
    }
  };

  useEffect(() => {
    window.addEventListener('scroll', _.debounce(setScroll, 1000));
    return () => window.removeEventListener('scroll', _.debounce(setScroll, 1000));
  });

  const justOneceFunction = () => {...}
}

Result: isPushed state is updated true only for a moment, but next time updated to false, so justOneceFunction() is called multiple times.

Upvotes: 0

Views: 1499

Answers (1)

Nilanka Manoj
Nilanka Manoj

Reputation: 3728

try:


useEffect(() => {
    window.addEventListener('scroll', _.debounce(setScroll, 1000));
  },[]);

Upvotes: 1

Related Questions