Home > database >  About Async in Alpine.js
About Async in Alpine.js

Time:03-28

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>

CodePudding user response:

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>
  • Related