this is my full alpine.js code
@{
int MOOD = 167;
}
<div x-data="{ 'showModal': false, variants: [] }" x-init="fetchVariants()" x-bind:data-product-id="@MOOD">
<!-- Trigger for Modal -->
<button type="button" @@click="showModal = true">Open Modal</button>
<!-- Modal -->
<div class="fixed inset-0 z-30 flex items-center justify-center overflow-auto" x-show="showModal">
<!-- Modal inner -->
<div class="max-w-3xl px-6 py-4 mx-auto text-left bg-white rounded shadow-lg" @@click.away="showModal = false"
x-transition:enter="motion-safe:ease-out duration-300" x-transition:enter-start="opacity-0 scale-90"
x-transition:enter-end="opacity-100 scale-100">
<!-- Title / Close-->
<div class="flex items-center justify-between">
<h5 class="mr-3 text-black max-w-none">Title</h5>
<button type="button" class="z-50 cursor-pointer" @@click="showModal = false">
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none"
stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
d="M6 18L18 6M6 6l12 12" />
</svg>
</button>
</div>
<div x-data>
<ul>
<template x-for="price in variants" :key="price">
<li>
<p>Price: <span x-html="price"></span></p>
</li>
</template>
</ul>
</div>
<div>
</div>
</div>
</div>
</div>
<script>
function fetchVariants() {
const productId = document.querySelector('[x-bind\:data-product-id]').getAttribute('data-product-id');
const url = `/Home/ProductDesc?ProductId=${productId}`;
fetch(url)
.then(res => res.json())
.then(res => {
variants = res.variant.map(item => ({ price: item.price }));
// Update the variants property with the new array of prices
Alpine.store('variants', variants);
})
.catch(error => {
console.error('Error:', error);
});
}
</script>
but trying different things i am not able to populate price. any idea what i am doing wrong here
I see this when entering console.log(Alpine.store(‘variants’))
2
Answers
Assuming that
fetchVariants()
can correctly fetch the data from the backend, the problem is that you put the data inAlpine.store('variants')
store object, but you are using the emptyvariants
local property in the component. You should use the$store
object in the template as well:Note: if
price
is really a price value, then it is not a good candidate for:key
because two items can have the same price. Use an unique id or something for the:key
.