So I am populating an array within a function but when i call on that array outside of the function im pretty sure it comes out as a string. The array works fine inside the function when I try to call [1] but if I try to do that outside the function it comes up as undefined.
Hope someone can help me out as i am almost finished this code but this is stopping me, thanks.
Just for reference in case its helpful, when I console log outside the function it comes up like this:
[]
0: 7604
1: 7606
2: 7607
3: 7608
Then within the function like this:
(4) [7604, 7606, 7607, 7608]
0: 7604
1: 7606
2: 7607
3: 7608
Here is also the code, I have removed the token for security purposes also ignore some parts of the code like posturl as they will be used once I have figured this out:
var geturl = "https://api.sendgrid.com/v3/asm/suppressions/ibrarr2000@gmail.com";
var posturl = "https://api.sendgrid.com/v3/asm/groups/"+ +"/suppressions";
var deleteurl = "https://api.sendgrid.com/v3/asm/groups/"+ +"/suppressions/ibrarr2000@gmail.com";
var token = "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";
let headers = new Headers();
let myData = {};
headers.append('Authorization', 'Bearer ' + token);
//supressionids = new Array();
var supressionids = [];
fetch(geturl, {
method: 'GET',
headers: headers,
}).then(function (res) {
return res.json();
}).then(function (data) {
myData = data;
buildSelect(data);
});
function buildSelect(d) {
let select = document.createElement('form');
d.suppressions.forEach(function (item) {
let label = document.createElement('label');
let option = document.createElement('input');
option.value = item.suppressed;
option.type = "checkbox";
option.setAttribute("onclick","task(event);");
option.id = item.id;
option.classList = "subbox";
option.textContent = item.name;
label.textContent = item.name;
select.appendChild(label);
select.appendChild(option);
supressionids.push(item.id);
let br = document.createElement('br');
select.appendChild(br);
if(JSON.stringify(item.suppressed) == 'false'){
option.setAttribute("checked", "checked");
}
});
document.querySelector('body').appendChild(select);
console.log(supressionids);
}
console.log(supressionids);
function task(e) {
if(e.target.checked){
fetch(deleteurl, {
method: 'DELETE',
headers: headers,
});
} else {
fetch(posturl, {
method: 'POST',
body: JSON.stringify({ "recipient_emails": [ "ibrarr2000@gmail.com" ] }),
headers: headers,
});
}
}