Another use case for x-init
is using fetch
to call remote API to initialize the data.
Version
Alpine 3.8
x-init
Data is from remote API, not defined in x-data
.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<script src="https://unpkg.com/alpinejs" defer></script>
<title>Alpine</title>
</head>
<body
x-data="{ users: [] }"
x-init="users = await(await fetch('https://jsonplaceholder.typicode.com/users')).json()"
>
<ul>
<template x-for="x in users">
<li x-text="x.name" />
</template>
</ul>
</body>
</html>
Line 9
<body
x-data="{ users: [] }"
x-init="users = await(await fetch('https://jsonplaceholder.typicode.com/users')).json()"
>
<ul>
<template x-for="x in users">
<li x-text="x.name" />
</template>
</ul>
</body>
x-data
: defineusers
variable, which is an empty Arrayx-init
: usefetch
to call remote API and initialize the datax-for
: iterate through the non-empty Array
Conclusion
x-init
supports async function, and we can useawait
directly inx-init