Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

145
Visualizações
How to pass React state variable into setInterval function

I created a drag and drop menu and so far everything works, however, I have run into a small coding problem for my last step. I need to get the menu of items to automatically scroll when the dragged item is towards the bottom of the container (or top). I decided to structure it so that when the cursor dragging the item falls below a specific range towards the bottom, a scroll function will trigger and continually scroll down at a pace I can set. In order to achieve this I set up a setInterval function and will continually call a scrollBy function.

My issue is that In order to stop the setInterval and call clearInterval, I need to know when the position of the cursor is no longer in that range. Every time the function is called in setInterval, it takes a snapshot of the current state variables. Instead of updating the state of those variables (yAxis position) within the function, it is stuck on the first value it gets.

The yPoisiton is obtained with the window.event.clientY from another component.

    document.onmousemove = (e) => {
      if (dragging.state) {
        var newYPos = window.event.clientY;
        setYPos(newYPos);
        handleScroll(newYPos, dragging.state);

The rest of the code goes as follows:

  const menuContainer = useRef();
  const [scrolling, setScrolling] = useState(false);
  const [yPos, setYPos] = useState(null);
  const [dragging, setDragging] = useState({
    state: false,
    index: null,
    y: null,
    height: null,
  });

  function continueScrolling() {
    console.log("continueScrolling function");
    console.log(yPos); // Same value even after updating via setYPos) 
    const date = new Date(); 
    console.log(date.toLocaleTimeString()); //Different values in accordance to the time
  }

  console.log("Index.js yPos");
  console.log(yPos); // Different values every render when dragging
  const handleScroll = (draggingYPos, isDragging) => { // This is triggered onMouseMove in another component
    if (
      draggingYPos >
        menuContainer.current.getBoundingClientRect().bottom - 100 &&
      isDragging
    ) {
      setScrolling(true); // On the first cycle scrolling == false and executes the setInterval function. Each subsequent call is then skipped. 
      if (scrolling) {
        return;
      } else {
        var intr = setInterval(function () {
          continueScrolling(); // Different method of testing and trying to get the current yPos in the function

//Commented but shows a bit of what I'm trying to accomplish
          // if (
          //   !(
          //     yPos >
          //       menuContainer.current.getBoundingClientRect().bottom - 100 &&
          //     dragging.state
          //   )
          // )
          //   clearInterval(intr);
        }, 1000);

Please let me know if there is more information you need or anything else I can clarify.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

This is a temporary solution I found to my problem, however, I would still like to know a more proper and robust solution if anyone has one, as well as information as to the scope of functions, React state, and how to pass them between one another.

I realize that it is not recommended to mutate states directly, however, this is my only current working solution. If I create a temporary value and pass in the setInterval, it will call setInterval a second time and will still be active after clearing it.

If I declare a global const variable, I cannot reassign the variable with setInterval. When I declared a global variable with var, the setInterval function continued even after I cleared it.

Adjusted code:

const [scroll, setScroll] = useState(null);

const handleScroll = (draggingYPos, isDragging) => {
    if (
      draggingYPos >
        menuContainer.current.getBoundingClientRect().bottom - 100 &&
      isDragging
    ) {
      setScrolling(true);
      if (scrolling) {
        return;
      } else {
        var count = 0;
        if (
          !(
            yPos > menuContainer.current.getBoundingClientRect().bottom - 100 &&
            dragging.state
          )
        ) {
          setScroll(
            setInterval(function () {
              count += 1;
              console.log(count);
            }, 1000)
          );
        }
      }
    } else {
      console.log("Not Scrolling");
      setScroll(clearInterval(scroll));
      setScrolling(false);
    }
  };



about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda