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