Alpine.js Playground
Examples Newsletter

Data Fetch Example

charizard

charizard

blaze solar-power
<div 
  x-data="pokeSearch()" 
  x-init="fetchPokemon()" class="mx-auto flex flex-col p-10"
>
  <div class="flex flex-row">
    <input type="text" name="pokemonSearch" 
      x-model="pokemonSearch" class="flex w-2/3 bg-white focus:outline-none focus:shadow-outline border border-gray-300 rounded-lg py-2 px-4 appearance-none leading-normal"
    >
    <button type="submit" 
      @click="fetchPokemon()" class="flex bg-blue-500 text-white font-bold py-2 px-4 rounded opacity-50 cursor-not-allowed" :class="[ isLoading ? 'opacity-50 cursor-not-allowed' : 'hover:bg-blue-700' ]" :disabled="isLoading" disabled="disabled"
    >
      Search
    </button>
  </div>
  <template 
    x-if="pokemon"
  >
    <div class="flex flex-row pt-10">
      <div class="flex mr-4">
        <img :src="pokemon.sprites.front_default" :alt="pokemon.name">
      </div>
      <div class="text-sm justify-center flex flex-col">
        <h3 class="text-gray-900 text-sm font-bold uppercase leading-none mb-2" 
          x-text="pokemon.name"
        ></h3>
        <div class="flex flex-row flex-wrap">
          <template 
            x-for="abilityObj in pokemon.abilities" :key="abilityObj.ability.url"
          >
            <span 
              x-text="abilityObj.ability.name" class="flex bg-gray-200 rounded-full px-3 py-1 text-xs font-semibold text-gray-700"
            ></span>
          </template>
        </div>
      </div>
    </div>
  </template>
  <script type="text/javascript">
    function pokeSearch() {
      return {
        pokemonSearch: "charizard",
        pokemon: null,
        isLoading: false,
        fetchPokemon() {
          this.isLoading = true;
          fetch(`https://pokeapi.co/api/v2/pokemon/${this.pokemonSearch}`)
            .then((res) => res.json())
            .then((data) => {
              this.isLoading = false;
              this.pokemon = data;
            });
        },
      };
    }
  </script>
</div>

💥 Subscribe for Early Access to the Alpine.js Handbook 📖 💥