Fetch Data from API in Alpine JS

Every component in Alpine starts with the x-data directive. x-data directive defines the reactive data for that component to reference. x-data can only use a sync function. Otherwise, you may encounter "DOMException: Failed to execute 'querySelectorAll'".

Call fetch in x-init



<div class="p-6"
x-data="{items: [], visibleItems: 3}"
x-init="
	fetch('https://invest.bangtech.com/webs/api/Stock/StockQuote?format=json&s=AAPL,AMZN,BA,BAC,CAT,CVS')
	.then(response => response.json())
	.then(data => items = data.slice(0, 5));
">
	<template x-for="(it,id) in items">
		<div
			class="border p-4 mb-4 flex justify-between items-center"
			x-transition
		>
			<div
				class="bg-blue-500 w-12 h-12 rounded-full text-white text-center flex justify-center items-center"
				x-text="id + 1"
			>
			</div>
		</div>		
	</template>
</div>          
 

Call async function in x-init


<script>
function loadData() {
	return {
		items: [],
		visibleItems: 3,
		async doLoadData()
		{
		  fetch('https://invest.bangtech.com/webs/api/Stock/StockQuote?format=json&s=AAPL,AMZN,BA,BAC,CAT')
		 .then(resp => resp.json())
		 .then(data => { this.items = data; });       
		}
	}
}
</script>
<div class="p-6"
 x-data="loadData()"
 x-init="items = await doLoadData()">
	<template x-for="(it,id) in items">
		<div
			class="border p-4 mb-4 flex justify-between items-center"
			x-transition
		>
		   <div
				class="bg-blue-500 w-12 h-12 rounded-full text-white text-center flex justify-center items-center"
				x-text="id + 1"
			>
			</div>
		</div>
	</template>
</div>
 

Demo Fetch Data from API in Alpine JS