I am currently working on developing an application using pure javascript and Web Components. My goal is to incorporate the MVC Pattern, but I have encountered a challenge with asynchronous calls from the model.
Specifically, I am creating a meal-list
component that retrieves data from an API in JSON format:
[
{
id: 1,
name: "Burger",
},
]
The issue arises when I attempt to pass this data from the model to the controller, and then to the view.
meals.js (Model)
export default {
get all() {
const url = 'http://localhost:8080/meals';
let menu = [];
fetch(url, {
method: 'GET',
headers: {
'Content-Type': 'application/json'
},
}).then(res => {
return res.json()
}).then(data => {
console.log(data);
menu = data;
});
return menu;
},
}
This is the approach I took to fetch data from the API.
meal-list.component.js (Controller)
import Template from './meal-list.template.js'
import Meal from '../../../../data/meal.js'
export default class MealListComponent extends HTMLElement {
connectedCallback() {
this.attachShadow({mode: 'open'});
this.shadowRoot.innerHTML = Template.render(Meal.all);
}
}
if (!customElements.get('mp-meal-list')) {
customElements.define('mp-meal-list', MealListComponent);
}
meal-list.template.js (View)
export default {
render(meals) {
return `${this.html(meals)}`;
},
html(meals) {
let content = `<h1>Menu</h1>
<div class="container">`;
// Display the data from the API using meals.forEach
return content + '</div>';
},
}
My main struggle lies in returning the asynchronous data from the model to the view. When attempting to simply return the data, it is undefined. Saving the data into an array also does not work. I have considered returning the entire fetch()
method, but this returns a promise, which I believe the controller should not handle.
I have explored numerous resources, such as a notable thread on How do I return the response from an asynchronous call?, but have yet to find a viable solution tailored to my specific scenario.