Next.js Discord

Discord Forum

detecting holding finger

Unanswered
Mandarin fish posted this in #help-forum
Open in Discord
Mandarin fishOP
Hi, I need to detect the pinch of the finger on the screen like if the finger is held on the screen for more than 2 seconds then the value of the variable isOpen will be true

9 Replies

Plott Hound
something like this should work:

import { useState } from 'react';

const TouchComponent = () => {
  const [isOpen, setIsOpen] = useState(false);

  // Timer reference
  let timer = null;

  const handleTouchStart = () => {
    // Start a timer when the touch starts
    timer = setTimeout(() => {
      // Set isOpen to true after 2 seconds
      setIsOpen(true);
      console.log('Finger held for 2 seconds, isOpen:', isOpen);
    }, 2000); // 2 seconds
  };

  const handleTouchEnd = () => {
    // Clear the timer if the touch ends before 2 seconds
    clearTimeout(timer);
  };

  return (
    <div
      onTouchStart={handleTouchStart}
      onTouchEnd={handleTouchEnd}
      style={{ width: '100vw', height: '100vh', backgroundColor: isOpen ? 'lightgreen' : 'lightgrey' }}
    >
      <p>Touch and hold the screen for 2 seconds</p>
      <p>{`isOpen: ${isOpen}`}</p>
    </div>
  );
};

export default TouchComponent;
Mandarin fishOP
this not working
Plott Hound
also make sure to clear the timer if the component unmounts to prevent any potential memory leaks

useEffect(() => {
  return () => {
    if (timer) {
      clearTimeout(timer);
    }
  };
}, []);
@Mandarin fish this not working
Plott Hound
you wanna share some logs then?
@Plott Hound you wanna share some logs then?
Mandarin fishOP
without errors, it just doesn't work.
@Mandarin fish without errors, it just doesn't work.
Serbian Hound
Did you make sure to set 'use client' on that component? Since useState requires it to be a client component
maybe
it's problem with headless ui