Akan Udosen
Akan Udosen

Reputation: 71

Alpinejs x-if is not being triggered

I have data that I am pulling from ajax. And I want this data display only when it is successfully pulled.

import Alpine from 'alpinejs'
import axios from 'axios'

const http = axios.create({
    baseURL: 'url',
})

window.axios = http

window.Alpine = Alpine


document.addEventListener('alpine:init', () => {
    Alpine.data('cart', () => ({
        items: null,

        init(){
            window.axios.get('wc/store/cart')
                .then(({data})=>{
                    this.items = data
                    console.log(this.items)
                }).catch(error => {
                console.log(error.toString())
            })
        },

        
    }))
})

Alpine.start()

Now I am using this in my template

<div x-data="cart">

<template x-if="items">      
      <h1>Shopping Cart</h1>
      <!-- display items here --> 
</template
</div>

The thing is, the h1 element is displayed but not the data from ajax.

Am I doing anything wrong. I am pretty confidence this should work.

Upvotes: 1

Views: 2284

Answers (1)

Yinci
Yinci

Reputation: 2480

You're not displaying your items. Keep in mind that template tags require a single root element only.

<div x-data="card">
    <template x-if="items">
        <div>
            <h1>Shopping Cart</h1>
            <template x-for="item in items">
                <div>
                    <h2 x-text="item.text"></h2>
                </div>
            </template>
        </div>
    </template>
</div>

Upvotes: 3

Related Questions