Search code examples
javascripthtmlfetch

How to save JSON output from fetch into a variable and use it after in Javascript?


I have this fetch function that gets me JSON data from my AWS API


async function pullData() {
    const response = await fetch(api_url);
    const data = await response.json();
    //console.log(data)
    return data
}

pullData()
    .then(response => {
        console.log('SUCCESS')
    })  
    .catch(error => {
        console.log('ERROR!')
        console.error(error)
    }) 

var test1 = pullData()

However, I cant seem to get the JSON data from this fetch into my Javascript on my HTML page to display the JSON data in a table

<script>
function CreateTableFromJSON() {
        var myBooks = test1

        // EXTRACT VALUE FOR HTML HEADER. 
        // ('Book ID', 'Book Name', 'Category' and 'Price')
        var col = [];
        for (var i = 0; i < myBooks.length; i++) {
            for (var key in myBooks[i]) {
                if (col.indexOf(key) === -1) {
                    col.push(key);
                }
            }
        }

        // CREATE DYNAMIC TABLE.
        var table = document.createElement("table");

        // CREATE HTML TABLE HEADER ROW USING THE EXTRACTED HEADERS ABOVE.

        var tr = table.insertRow(-1);                   // TABLE ROW.

        for (var i = 0; i < col.length; i++) {
            var th = document.createElement("th");      // TABLE HEADER.
            th.innerHTML = col[i];
            tr.appendChild(th);
        }

        // ADD JSON DATA TO THE TABLE AS ROWS.
        for (var i = 0; i < myBooks.length; i++) {

            tr = table.insertRow(-1);

            for (var j = 0; j < col.length; j++) {
                var tabCell = tr.insertCell(-1);
                tabCell.innerHTML = myBooks[i][col[j]];
            }
        }

        // FINALLY ADD THE NEWLY CREATED TABLE WITH JSON DATA TO A CONTAINER.
        var divContainer = document.getElementById("showData");
        divContainer.innerHTML = "";
        divContainer.appendChild(table);
    }
</script>

What should I write instead of "var myBooks = test1" to link the 2 code chunks together and get the output on my HTML page?

Many thanks in advance!


Solution

  • I think I found the problem!

    var test1 = pullData();

    doesn't return the actual response json data, rather it returns a Promise. Make the function CreateTableFromJson an async function and download the data inside it or modify the function as ...

    pullData()
        .then(CreateTableFromJSON)  
        .catch(console.error);
    
    function CreateTableFromJSON(jsonData) {
       // work the jsonData here 
    }