Search code examples
javascriptasync-awaitmithril.js

Updating component with async function in mithirl.js


I'm trying to get some initial data for a component using an async function oninit then updating that component each time 'Show more' button is clicked.

Here is the component:

const Listings = {
    oninit: async (vnode) => {
        vnode.state.data = await get_listings()
        console.log("Ok has data ", vnode.state.data)
    },
    view: vnode => {

        console.log("NOK undefined ", vnode.state.data)

        return m("section.anunturi.mb-4", [

            vnode.state.data.map(data => {
                return m("span", JSON.stringify(data, undefined, 2))
            }),

            m("button", {class:"btn", onclick:get_listings}, "Show more")
        ])
    }
}

oninit gets the data from the async function but is not saved in vnode.state.data


Solution

    1. on first load the data is not ready right away and so data is undefined and throws a javascript error, add a condition to prevent displaying the data until the data is ready vnode.state.data ? /* display it */ : /* display loading message */

    2. once the data becomes ready you need to tell mithril to redraw, [redraw], by calling m.redraw(), I added that call at the end of oninit, which based on Mozilla's async/await documentation should be treated as the contents of a then() function of a promise ([async], ie. called after the awaited data is back

    [async] https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function

    [redraw] https://mithril.js.org/redraw.html

    const Listings = {
        oninit: async (vnode) => {
            vnode.state.data = await get_listings()
            console.log("Ok has data ", vnode.state.data)
            m.redraw();
        },
        view: vnode => {
    
            console.log("NOK undefined ", vnode.state.data)
    
            return m("section.anunturi.mb-4", [
    
                vnode.state.data ? vnode.state.data.map(data => {
                    return m("span", JSON.stringify(data, undefined, 2))
                }) : "Waiting for data...",
    
                m("button", {class:"btn", onclick:get_listings}, "Show more")
            ])
        }
    }