I auto a refresh a page (say Page1) in every 5 second interval using setTimeout and callback function.
When I move to a new page (say Page2), its going new page and after few seconds again returning to Page1.
I tried window beforeunload event listener, react useBeforeUnload, nothing works. Here is the minimal code to reproduce the issue.
const SampleTestStats = () => {
let allowStateChange = true;
let sampleTimeOut = null;
let SAMPLE_TEST_STATS_REFRESH_TIME = 5000;
const [result, setResult] = useState([{ tid: 0, tcname: "none"},]);
const user = JSON.parse(localStorage.getItem('user'));
function refreshPage() {
sampleTimeOut = setTimeout(refreshPage, SAMPLE_TEST_STATS_REFRESH_TIME);
window.location.href = "/components/view/sampletest/stats";
}
useBeforeUnload(
React.useCallback(() => {
console.log('In useBeforeUnload');
allowStateChange = false;
clearTimeout(sampleTimeOut);
})
);
const fetchTestStats = async () => {
try {
const res = await axios.post('/test/current/active/data',
{uid: user.uid, email: user.email} ,
{headers: {
'Authorization': user.jwt,
}}).then(
function (res) {
if(res.status === 200) {
if(allowStateChange) {
let newResult = {tid: res.data[0].tid, tcname: res.data[0].testname};
setResult([newResult]);
}
}
});
}catch(err) {
}
}
useEffect ( () => {
fetchTestStats();
}, []);
sampleTimeOut = setTimeout(refreshPage, SAMPLE_TEST_STATS_REFRESH_TIME);
return (`My simple refresh test page, test id = ${result[0].tid} and test name = ${result[0].tcname}.`);
}
Can somebody please help me, when I move to a new page Page2 again automatically it should not come back to old page Page1.