點燈坊

失くすものさえない今が強くなるチャンスよ

Using x-init to Fetch Data from API

Sam Xiao's Avatar 2022-02-12

Another use case for x-init is using fetch to call remote API to initialize the data.

Version

Alpine 3.8

x-init

fetch000

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 : define users variable, which is an empty Array
  • x-init : use fetch to call remote API and initialize the data
  • x-for : iterate through the non-empty Array

Conclusion

  • x-init supports async function, and we can use await directly in x-init

Reference

Alpine, x-init