Trying to load an Alpine store with values (a list of arrays) from an API call. The fetch returns a promise, so looking for the best way to load this diretly:
document.addEventListener('alpine:init', () => {
Alpine.store('myStore', {
my_data: fetch('/api/1')
.then(response => response.json())
})
})
I’m not committed to fetch but whatever’s easiest to add to the store directly.
Invert it. Fetch the data first then create the store once it's resolved
document.addEventListener("alpine:init", async () => {
const res = await fetch("/api/1");
if (!res.ok) {
throw new Error(`${res.status}: ${await res.text()}`);
}
Alpine.store("myStore", {
my_data: await res.json(),
});
});