简体   繁体   中英

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.

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)
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM