Posts Learn Components Snippets Categories Tags Tools new About
/

How to Fetch API in Alpine.js

Learn how to fetch API in Alpine.js using the native fetch JS to get external resource

Created on Nov 18, 2021

8 views

In this short snippet, you will learn how to fetch an external API in Apline.js. We'll be using the native Fetch API available to JavaScript.

Step 1: Install Alpine.js


First, you have to install Alpine.js using NPM or Yarn but If you do prefer the easy road then let's just reference the CDN. At the time of this writing, the version is 3.5.0 so if you are reading it on the future do refer to the documentation.
<script defer src="https://unpkg.com/[email protected]/dist/cdn.min.js"></script>

Step 2: Define Alpine.js Data


Now you will have to define the Alpine.js data and it's as simple as calling the x-data. For this example, we'll be calling the Pokemon API so we can later on print some pokemon stats to the console.
<div x-data="{ pokemon: null }"></div>
The API endpoint will be as follows.
https://pokeapi.co/api/v2/pokemon/{pokemon-name-here}

Step 3: Call the Ajax From Alpine.js


To call an ajax using the "Fetch API" you can define it from within the x-init attribute where it will be called when Alpine.js initializes. The pokemon we'll be calling is "Pikachu".
https://pokeapi.co/api/v2/pokemon/pikachu
Do note that the logic can be extracted to its own function. For now, the logic will be as follows.
function getPokemon() {
    fetch('https://pokeapi.co/api/v2/pokemon/pikachu')
        .then((response) => response.json())
        .then((json) => this.pokemon = json);
}

Step 4: Attach Fetch Function to Alpine.js


Now to attach the function you can specify your code within the x-data attribute.
<div x-data="{
    pokemon: null,

    getPokemon() {
        fetch('https://pokeapi.co/api/v2/pokemon/pikachu')
            .then((response) => response.json())
            .then((json) => this.pokemon = json);
    }
}" x-init="getPokemon()"></div>
Now when you load the page it will automatically ajax and retrieve the pokemon details. To print out the details you can make use of the x-text inside the "div" tag itself.
<div x-data="{
    pokemon: null,

    getPokemon() {
        fetch('https://pokeapi.co/api/v2/pokemon/pikachu')
            .then((response) => response.json())
            .then((json) => this.pokemon = json);
    }
}" x-init="getPokemon()">
    <p x-text="pokemon.abilities[0].ability.name"></p>
    <p x-text="pokemon.abilities[1].ability.name"></p>
</div>
If you find this snippet to be useful do make sure to share it with your friends and cheers! happy coding.

Other Reads

If you like our tutorial, do make sure to support us by being our Patreon or buy us some coffee ☕️

new

PostSrc Code Components

Collection of Tailwind CSS components for everyone to use. Browse all of the components that are right for your project.

View Components
)