[Mise] Refetch API data when a state value changes with the `$watch` property in Alpine JS

In this lesson, we build a little app that fetches dog photos from the dog.ceo API, based on a "breed" search field. We want the API call to happen again when the search value changes, and to do so we use the $watch property from Alpine JS, which lets us define what state property we want to watch, and what callback function to run when a change happens.

We also use the debounce modifier on the x-model property to avoid firing an API call on each keystroke.

 

复制代码
<div x-data="dogFetcher()" x-init="init">
  
  <!-- Search field -->
  <label>What breed?</label>
  <input type="text" x-model.debounce.750="breed">

  <!-- API error -->
  <template x-if="fetchStatus === 'error'">
    <p class="error">There was something wrong with the API call, please try again.</p>
  </template>

  <!-- Empty search field value -->
  <p x-show="!breed" class="prompt">Let's go fetch some pups!</p>

  <!-- Fetching dog breed -->
  <div x-show="fetchStatus === 'loading'" class="spinner"></div>

  <template x-if="breed && fetchStatus === 'idle'">
    <div>
      <!-- Failed search -->
      <template x-if="data.status === 'error'">
        <p class="error" x-text="data.message"></p>
      </template>  

      <!-- Puppy pic!! -->
      <template x-if="data.status === 'success'">
        <img :src="data.message" alt="cute pup" />
      </template>
    </div>  
  </template>
</div>

<script>
  function dogFetcher() {
    return {
      breed: 'corgi',
      fetchStatus: 'loading',
      data: null,
      init() {
        this.$watch('breed', () => {
          this.fetchDogs();
        });
        this.fetchDogs();
      },
      fetchDogs() {
        this.fetchStatus = 'loading',
        fetch(`https://dog.ceo/api/breed/${this.breed}/images/random`)
          .then(res => {
            if (!res.ok) {
              this.fetchStatus = 'error'
            }
            return res.json()
          })
          .then(data => {
            this.fetchStatus = 'idle'
            this.data = data
          })
          .catch(error => {
            this.fetchStatus = 'error'
            console.log({ error })
          })
      }
    }
  }
</script>
复制代码

 

posted @   Zhentiw  阅读(378)  评论(0编辑  收藏  举报
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2019-05-16 [Algorithm] Prime factorization of a number
2017-05-16 [Recompose] Compute Expensive Props Lazily using Recompose
2017-05-16 [Recompose] Set the HTML Tag of a Component via a Prop using Recompose
2017-05-16 [Recompose] Render Nothing in Place of a Component using Recompose
2017-05-16 [Recompose] Replace a Component with Non-Optimal States using Recompose
2017-05-16 [Recompose] Show a Spinner While a Component is Loading using Recompose
2016-05-16 [PWA] 8.Unobtrusive update: Delete old cache and only keep one, hard refresh to let new SW to take control
点击右上角即可分享
微信分享提示