• [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>
  • 相关阅读:
    [LeetCode] Strobogrammatic Number III
    [LeetCode] Strobogrammatic Number II
    [Codeforces 1253E] Antenna Coverage
    [CodeForces 466C] Number of Ways
    UVa 806 四分树
    Uva 1572 自组合
    UVa Sculpture(离散化 floodfill)
    Uva 4916 Selling Cells(随机算法)
    UvaLive 4863 Balloons(贪心)
    UvaLive 4872 Underground Cables (最小生成树)
  • 原文地址:https://www.cnblogs.com/Answer1215/p/12900861.html
Copyright © 2020-2023  润新知