I previously had a simple component that looked something like this, but previously the getIsLoggedIn method was synchronous. We recently had to change that method to async, so I tried adding the await keyword to it and changing the view() to be async view(), but this doesnt seem to work:
const welcomePageComponent = {
messages: {
msg1: 'message if logged in',
msg2: 'message if not logged in',
},
view({ state }) {
let isLoggedIn = getIsloggedIn();
let myMsg = isLoggedIn ? this.messages.msg1 : this.messages.msg2;
return m('#welcome', [
m('.semi-trans-blk-panel', [
m('.welcome-wrapper', [
m('h4.welcomeMsg', [
m('br'), myMsg
])
])
])
]);
}
}
How can I go about calling an async function and using its return value inside my view()?
The problem is that the application view must be computed synchronously on each draw; if a promise returned by a view were to trigger a new view computation on resolution, the next computation would still resolve to a promise, so you'd be stuck in a loop.
The solution is to instantiate an extra data point to track whether the promise has resolved, and an
oninitlifecycle method to call the promise and change the relevant data once, on initialisation, and then redraw. Finally, we modify the view function to return nothing unless the authentication data is available.