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

123
Visualizações
Loop requests in react with axios

I have a socket defined in the backend that accepts continuous requests for the server. Now, I want to send requests continuously to the backend API, until a stop button is pressed. So, I can use a loop (BAD PRACTICE). The problem is that it never checks the updated state. So, How can I implement this with the best possible coding practice?

  1. I'm using two different pages in Next.JS for client and server. The server has a simple button to start and stop the server, and when the button is set to start, it should continuously accept requests and update the response state, and when the button is set to stop, it should stop requesting any more.
const [close, closeButton] = useBoolean() // State for close button
let req;
proto ? req = 'UDP' : req = 'TCP' // There is a checkbox to select the connection mode. proto is a state.
console.log(`Close button: ${close}`) // This state updates correctly. 

const onSubmit = async () => {
   while(!close)
        console.log(`Close button: ${close}`) // This state does not update while staying in the loop.
        const res = await serverRequest(req) 
        console.log(res.messageFromClient)
    }
}

So, how should I get this to run indefinitely until the close button is pressed. Should I use redux for the global state or is there a better way other than the while loop?

Client code for reference:

 const onSubmit = async values => {
        const clientData = await clientRequest({proto, JSON.stringify(values.message)})
        console.log(clientData)
        console.log(values.message)
    }

This code sends client data every time the message is sent from the client. So, in order to run the client, the server should continuously listen to requests. Whenever the client sends a request, the server should get a response and start the server once again, until the mode of connections is changed or the close button is pressed in the server-side code.

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

0

If you absolutely must use this code, and want it to access updated state then you could cache a copy of state in a React ref and refer to that instead.

const [close, closeButton] = useBoolean() // State for close button
const closeRef = React.useRef();

React.useEffect(() => {
  closeRef.current = close; // <-- cache close value when it updates
}, [close]);

const onSubmit = async () => {
  while(!closeRef.current) // <-- cached close state value
    console.log(`Close button: ${closeRef.current}`)
    const res = await serverRequest(req) 
    console.log(res.messageFromClient)
  }
}
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