Basically I wanted the data from JSON to be accessible outside of the xml function as I have multiple functions I want to use it for.
So when I first tried it out and tried logging it, it did show the arrays with the objects in it. But when I did the same but checked the length instead it came out as zero. I looked this up and found out that it happens because both functions are running synchronously. So I looked into promises and implemented it like this:
let allTasks = []
// Read data
const dataPromise = new Promise((resolve, reject)=>{
const xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status ==200) {
const myData = JSON.parse(this.responseText)
allTasks = allTasks.push.apply(allTasks, myData)
resolve()
}
}
xhttp.open("GET", "data.json", true);
xhttp.send();
})
dataPromise.then(()=>{
dataUse()
})
// Show data
dataUse = () =>{
console.log(allTasks)
// All variables
const todos = document.querySelector('.todo')
const todoInput = document.getElementById('new-todo')
const added = document.getElementById('added')
const itemsLeft = document.querySelector('.items-left > span')
allTasks.forEach((datas)=>{
const todo = document.createElement('div')
todos.appendChild(todo)
const input = document.createElement('input')
input.setAttribute('type', 'checkbox')
input.setAttribute('id', datas.name)
input.setAttribute('class', 'checks')
todo.appendChild(input)
const label = document.createElement('label')
label.setAttribute('for', datas.name)
label.setAttribute('class', `${datas.name} tasks`)
todo.appendChild(label)
const span = document.createElement('span')
label.appendChild(span)
const paragraph = document.createElement('p')
paragraph.innerHTML = datas.todo
label.appendChild(paragraph)
})
}
But now logging it gives me a number rather than the array with the objects, hence the function won't be able to do what it is suppose to.
So how do I fix this?
The problem is that you don't have to assign the return value of a push operation to the variable because the return value is the length of the array.
Just push into the array and the variable will have the latest content.
Instead of allTasks = allTasks.push.apply(allTasks, myData),
do allTasks.push(allTasks, myData).
It'll be good if you use const in place of let.
const allTasks = [];
allTasks.push(allTasks, myData);