0

So yeah, working on a project where I'm taking data from a text file on a web server and adding it to an array to display on an HTML document.

The text file on the web server, I'll just call values.txt, looks like this:

value b
value c
value d
value e
value f

This is the code of my current attempt:

const newArray = ["value a"];

const fileUrl = *url of values.txt*;
    fetch(fileUrl)
        .then(r => r.text())
        .then((text) => {
            const array2 = text.split("\n");

            for (let i = 0; i < array2.length; i++)
            {
                newArray.push(array2[i]);
            }
        })

document.getElementById("add").innerHTML += ("<br>Array test: " + newArray[1]);

In theory, newArray[1] should return value b, instead it returns as undefined.

1 Answers1

1

This is because of the asynchronous nature of the Fetch API. Move your code that update the DOM inside then block:

.then((text) => {
    const array2 = text.split("\n");

    for (let i = 0; i < array2.length; i++)
    {
        newArray.push(array2[i]);
    }
    //Update the DOM here
    document.getElementById("add").innerHTML += ("<br>Array test: " + newArray[1]);
});
Mamun
  • 66,969
  • 9
  • 47
  • 59