Handling asynchronous data fetching in Marko.js can be done using the onCreate or onInput lifecycle methods. Here is an example:
// user-profile.marko
<template>
<div>
<if(state.loading)>
Loading...
</if>
<else>
<h1>${state.user.name}</h1>
<p>${state.user.bio}</p>
</else>
</div>
</template>
<script>
module.exports = class {
async onCreate(input) {
this.state = {
loading: true,
user: null
};
const response = await fetch(`https://api.example.com/users/${input.userId}`);
const user = await response.json();
this.state = {
loading: false,
user
};
}
};
</script>
In this example, the component fetches user data asynchronously when it is created, updating its state once the data is retrieved.