'Handlebars template not rendering data inside of then
Im having a problem with handlebars.
This code works:
const getFacilitators = async () => {
const { data } = await axios.get(`${api_url}/facilitator/list`, {
headers: {
'Authorization': `Bearer ${sessionStorage.getItem('id_token')}`
}
})
return data.Items;
}
getFacilitators()
.then(facilitators => {
if (document.querySelector("#facilitatorTemplate")) {
var facilitatorTemplate = Handlebars.compile(document.querySelector("#facilitatorTemplate").innerHTML);
document.querySelector("#facilitatorSelect").innerHTML = facilitatorTemplate({ facilitators });
//element.value = currentFacilitator.id;
}
});
But it is tripping over a race condition where the currentFacilitator.id is not loaded yet. When I try to put it in a then after the axios call to get that value then it does not seem to render the values from facilitators
.then(() => getFacilitators())
.then(facilitators => {
if (document.querySelector("#facilitatorTemplate")) {
var facilitatorTemplate = Handlebars.compile(document.querySelector("#facilitatorTemplate").innerHTML);
document.querySelector("#facilitatorSelect").innerHTML = facilitatorTemplate({ facilitators });
document.querySelector("#facilitatorSelect").value = currentFacilitator.id;
}
});
Here is the HTML
<template id="facilitatorTemplate">
<select type="text" class="form-control" name="facilitatorId" list="facilitatorsDatalist" autocomplete="off">
{{#each facilitators}}
<option value="{{id}}">{{email}}</option>
{{/each}}
</select>
</template>
<div id="facilitatorSelect">waiting</div>
Full code is visible here https://github.com/lindsaymacvean/rp/blob/main/docs/scripts/group.js
Solution 1:[1]
I went line by line through my HTML and realised that one of the other Handlebar renders was taking the innerHTML which included the template I wanted to render. So in effect the HTML was not available by the time it got to the then in the chain where I wanted to render my second set of data.
My solution was to store the data from the first axios call in a variable that could be accessed later. Then render all the data in one handlebars template in the last then in the chain.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | lindsaymacvean |

