I have the below code which is an event listener for a chatbot.
The userType value is not being preserved or passed from the first if statement to the second if statement, the value is undefined.
How can I prevent the userType value from being cleared by the second if statement?
q('handleEvents', function(name, data) {
var userType;
if (name === 'QCP') {
userType = "CP";
console.log(userType);
}
if (name === 'EC') {
console.log('EC found');
console.log(userType);
window.dataLayer = window.dataLayer || [];
window.dataLayer.push({
'event': 'qlc',
'qUserType': userType
});
}
});
>Solution :
You could put userType outside the function. You could also seal it in a block so it could be visible to the event handler only (like a static function variable), avoid using var in the modern JS, learn about let and const. That way the variable will be preserved between the event listener’s calls.
Also use else if to avoid the second check if the first is true:
{
let userType;
q('handleEvents', function(name, data) {
if (name === 'QCP') {
userType = "CP";
console.log(userType);
} else if (name === 'EC') {
console.log('EC found');
console.log(userType);
window.dataLayer = window.dataLayer || [];
window.dataLayer.push({
'event': 'qlc',
'qUserType' : userType
});
}
});
}