asynchronousasync-awaitalpine.js

AlpineJS aynchronous data loading


I'm looking into AlpineJS for the first time and I'm trying to load some data into the x-data attribute.

I have something like

<body x-data="data">
...

in my HTML. Inside data I store all the data and functions I use later (it's a very simple SPA)

document.addEventListener('alpine:init', () => {
  Alpine.data('data', () => ({
    foo: 1,
    bar: 2,
    ...
  }));
}

Everything works fine until all the variables are synchronous, but now I need to assign to one variable some data I get asynchronously from the DB.

I tried with something simple like

document.addEventListener('alpine:init', () => {
  Alpine.data('data', async () => ({
    foo: 1,
    bar: await getData(),
    ...
  }));
}

which unfortunately does not work. I get a Uncaught ReferenceError: VARIABLE_NAME is not defined for each variable inside data.

How can I solve this issue? There is a standard way to handle situations like this one?


Solution

  • You can assign the async data in the init() method, and remove the async from the main data() function:

    document.addEventListener('alpine:init', () => {
    
        Alpine.data("data", () => ({
    
            foo: 1,
            bar: null,
    
            init: async function () {
    
                this.bar = await this.getData();
            },
    
            getData: async function () {
    
                return Promise.resolve("abc");
            }
        }));
    });