mario
mario

Reputation: 13

About Async in Alpine.js

https://alpinejs.dev/advanced/async

I tried as per the URL above and nothing showed up.

Where is the problem?

<script defer src="https://unpkg.com/[email protected]/dist/cdn.min.js"></script>
<!-- 〇 -->
<h1 x-data="{ message: 'I ❤️ Alpine' }" x-text="message"></h1>

<!-- × -->
<span x-text="getLabel()"></span>
<script>
  function getLabel() {
    return 'Hello World!'
  }
</script>

<!-- × -->
<span x-text="await getLabel()"></span>
<script>
  async function getLabel() {
    let response = await fetch('...')
    return await response.text()
  }
</script>

Upvotes: 0

Views: 3458

Answers (1)

Dauros
Dauros

Reputation: 10517

The Alpine.js documentation omits this information in the advanced chapters, because it assumes the reader is already familiar with the basics at that point. So you always have to have an x-data directive in order to activate an Alpine.js component. If you don't have any reactive data, just use an empty x-data attribute on the element (or any parent element).

<span x-data x-text="await getLabel()"></span>
<script>
  async function getLabel() {
    let response = await fetch('...')
    return await response.text()
  }
</script>

Upvotes: 4

Related Questions