I needed to access the data from JSON outside of the xml function so that I could use it in multiple functions. When I initially logged the data, it displayed arrays with objects in it. However, when I checked the length instead, it returned zero. After researching, I discovered that this discrepancy occurred because both functions were running synchronously. To address this, I delved into promises and implemented the following:
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)
})
}
However, after logging the data now shows a number rather than an array with objects, hindering the proper functioning of the function.
So, how can I rectify this issue?