In my JavaScript project, I am attempting to refresh the page once a user is logged in by polling to continuously monitor user data. Here is the code snippet below:
var check;
function poll(){
return $.ajax({
url: 'http://localhost:3000/poll',
type:'GET',
xhrFields: { withCredentials: true }
}).done(function(data){
console.log(data); // if the user is logged in, the server sends the user object; otherwise, it doesn't
if(typeof data.name !== "undefined"){
check = '1'; // The browser does not retain the value of 'check' as 1 after reload
window.location.reload();
} else {
setTimeout(function(){ poll(); }, 5000);
}
});
}
if(typeof check == 'undefined'){ // The issue arises on reload where the browser forgets that 'check = 1' was set before
setTimeout(function(){ poll(); }, 5000);
}
I aim to create a workflow where:
1) If the user is not logged in, the polling should continue to verify their login status.
2) Once the user logs in, the page should automatically reload and the polling should cease.