i have a button with which i start a test function:
<button type="button" onClick={startTestFrequencyList}>{
frequenciesTestRunning ? 'Stop Test Frequency' : 'Start Test Frequency'
}</button>
The startTestFrequencyList either starts the testFrequencyList or stops it.
const [stopTest, setStopTest] = useState(false);
const [frequenciesTestRunning, setFrequenciesTestRunning] = useState(false);
const startTestFrequencyList = () => {
if (frequenciesTestRunning) {
window.alert("Already testing")
setStopTest(true);
} else {
setFrequenciesTestRunning(true);
testFrequencyList();
}
}
Inside the startTestFrequencyList function i execute a lot of fetch calls in a loop. Which i want to stop if the user clicks the button again.
const testFrequencyList = async () => {
for (const item of frequencyList) {
try {
// Stop the fetching
if (stopTest) {
// STOP TEST
stopTest(false);
setFrequenciesTestRunning(false);
return;
}
const response = await fetch('http://127.0.0.1:8000/frequency/testWithRe/', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(item),
});
const testResult = await response.json();
// do something
} catch (error) {
console.error('Error:', error);
}
}
}
The problem is, whenever stopTest is set to true, nothing happens. It seems like the function does not get the newest state of stopTest.
