function addEntryToList(text) {
    var ul = document.getElementById("list");
    var li = document.createElement("li");
    li.appendChild(document.createTextNode(text));
    ul.appendChild(li);
}

let decoder = new TextDecoder();

/**
 *
 * @param {ReadableStreamGenericReader<Uint8Array>} reader
 * @returns {ReadableStreamGenericReader<Uint8Array> | undefined}
 */
function readDataFromStream(reader) {
    return reader.read().then(({ done, value }) => {
        // When no more data needs to be consumed, close the stream
        if (done) {
            return;
        }
        let jsonString = decoder.decode(value);
        let jsonData = JSON.parse(jsonString);
        addEntryToList(jsonData.message)
        // Enqueue the next data
        return readDataFromStream(reader);
    });
}

/**
 * @param {Promise<Response>} httpRequest to use
 */
function callEndless(httpRequest) {
    httpRequest.then(response => {
        const reader = response.body.getReader();
        return readDataFromStream(reader);
    }).catch((error) => {
        console.log("error", error);
    }).finally(() => {
        callEndless(fetch("http://localhost:8080"));
    });

}

callEndless(fetch("http://localhost:8080"));
