Search code examples
javascriptjqueryjsonasync-awaitfetch

Creating two asynchronous fetch requests


After using a fetch request to fill a dropdown box with fields obtained via a fetch request, we select one of those fields and the code should make another fetch request to obtain the data associated with the selected field.

However, while doing this, the second fetch request is not processing after the first. We figured taht was the case because if we use the second fetch request with a pre-set field (and not the one selected on the menu) it works as intended.

The script is as follows:

    <script>

    let result;

    let dropdown = document.getElementById('list-occurences');
    dropdown.length = 0;

    let defaultOption = document.createElement('option');
    defaultOption.text = 'Choose occurence to edit';

    dropdown.add(defaultOption);
    dropdown.selectedIndex = 0;

async function loadOcc() {
    const response = await fetch('https://safeandsoundpw.herokuapp.com/audits/status/0');
    const occ = await response.json();
    let option;
        
    for (let i = 0; i < occ.length; i++) {
        option = document.createElement('option');
        option.text = occ[i].fk_Audits_occurrence_id;
        option.value = occ[i].fk_Audits_occurrence_id;
        dropdown.add(option);
    }
    
    let selection = document.querySelector('#list-occurences');
        selection.addEventListener('change', () => {
            result = parseInt($('#list-occurences option:selected').val());
        });
    
    let response2 = await fetch(`https://safeandsoundpw.herokuapp.com/occurrences/$(result)`);
    const occ2 = await response.json();
    
    $.each(occ2, function (index, value) {
        console.log(value);
        $('#teamManager').append(`${value.fk_Occ_manager_id}`);
        $('#place').append(`${value.place}`);
        $('#date').append((`${value.start_date}`).slice(0,10).split("-").reverse().join("/"));
    });

    return occ;
}

console.log(result);
document.addEventListener("DOMContentLoaded", async () => {
    let occ = [];

    try {
        occ = await loadOcc();
    } catch (err) {
        console.log("Error!");
        console.log(err);
    }
    console.log(occ);
});

</script>

Thank you for your time.


Solution

  • The second fetch has to be inside the dropdown change handler.

    let selection = document.querySelector('#list-occurences');
    selection.addEventListener('change', () => {
      result = parseInt($('#list-occurences option:selected').val());
      
      let response2 = await fetch(`https://safeandsoundpw.herokuapp.com/occurrences/${result}`); // Fixed the brace issue here
      const occ2 = await response2.json();  // Await response2... The "2" was missing
      
      $.each(occ2, function (index, value) {
          console.log(value);
          $('#teamManager').append(`${value.fk_Occ_manager_id}`);
          $('#place').append(`${value.place}`);
          $('#date').append((`${value.start_date}`).slice(0,10).split("-").reverse().join("/"));
      });
        
    });