Reputation: 648
How can I bind data from a fetched response to a component?
My goal is to check if users current deliveryProvider (fetched from firestore) match a given provider name?
<template x-for="(provider, index) in Object.values(deliveryProviders.providers)" :key="provider">
<div>
<label>
<div class="relative flex justify-between border border-b-0 border-gray-200 p-3 md:pl-4 md:pr-6"
:class="{
'rounded-tl-md rounded-tr-md' : index === 0,
'rounded-bl-md rounded-br-md border-b': (Object.values(deliveryProviders.providers).length == index+1)}">
<div class="text-sm flex cursor-pointer">
<input name="deliveryProviders" type="checkbox" :value="provider.name"
class="focus:ring-indigo-500 h-4 w-4 text-indigo-600 border-gray-300 rounded"
:checked="user.deliveryProvider.includes(provider.name)">
<div class="ml-3">
<div class="font-medium text-gray-900" x-text="provider.name"></div>
<div class="text-sm block text-gray-500" x-text="provider.description">
</div>
</div>
</div>
</div>
</label>
</div>
This approach results in Cannot read property 'includes' of undefined
Upvotes: 0
Views: 910
Reputation: 900
Your script is trying to load while deliveryProviders
is undefined. Don't let it.
<div x-if="deliveryProviders !== undefined">
<template x-for="(provider, index) in Object.values(deliveryProviders.providers)" :key="provider">
<div>
<label>
<div class="relative flex justify-between border border-b-0 border-gray-200 p-3 md:pl-4 md:pr-6"
:class="{
'rounded-tl-md rounded-tr-md' : index === 0,
'rounded-bl-md rounded-br-md border-b': (Object.values(deliveryProviders.providers).length == index+1)}">
<div class="text-sm flex cursor-pointer">
<input name="deliveryProviders" type="checkbox" :value="provider.name"
class="focus:ring-indigo-500 h-4 w-4 text-indigo-600 border-gray-300 rounded"
:checked="user.deliveryProvider.includes(provider.name)">
<div class="ml-3">
<div class="font-medium text-gray-900" x-text="provider.name"></div>
<div class="text-sm block text-gray-500" x-text="provider.description">
</div>
</div>
</div>
</div>
</label>
</div>
</template>
</div>
The snippet above is using AJAX via the fetch interface to request data from the server. The only issue is that nothing is telling the AlpineJS script to wait for the data to populate. Placing the x-if
logic will skip the problematic code until the variable its depending on has loaded.
Upvotes: 2