Search code examples
javascriptjquerylaravellaravel-livewirealpine.js

Alpine.js 'paginationData is not defined' Error in Laravel Jetstream Component


I'm working on a Laravel Jetstream project with Alpine.js and Livewire. I'm encountering an error in my console indicating that paginationData is not defined, despite having imported it correctly into my app.js file and having declared it in a separate module.

Here's my current setup:

1. Import in app.js:

import Alpine from 'alpinejs';
import paginationData from './alpine/pagination-stepper.js';

Alpine.data('paginationData', () => paginationData);
Alpine.start();
console.log('Alpine started');

2. Definition of paginationData in pagination-stepper.js:

const paginationData = {
    currentPage: 1,
    perPage: 5,
    totalCount: 10,
    get paginatedData() {
        const start = (this.currentPage - 1) * this.perPage;
        const end = start + this.perPage;
        return Array.from({ length: this.totalCount }, (_, i) => i + 1).slice(start, end);
    },
    nextPage() {
        if (this.currentPage < Math.ceil(this.totalCount / this.perPage)) {
            this.currentPage++;
        }
    },
    prevPage() {
        if (this.currentPage > 1) {
            this.currentPage--;
        }
    }
};

export default paginationData;

3. Usage in welcome.blade.php:

<section x-data="paginationData">
    <div>
        Current Page: <span x-text="totalCount"></span>
    </div>
</section>

It does show the current page number

enter image description here

4. Error in Console:

Despite showing the page number, indicating that the code gets loaded successfully, I still get an error.

enter image description here

I've tried the following troubleshooting steps:

  • Verified that the import is correct and that paginationData is properly defined.
  • Cleared the Laravel cache with php artisan view:clear and php artisan cache:clear.
  • Restarted the development server.
  • Checked for conflicts with Livewire.

Despite these attempts, the error persists. What could be causing this issue, and what should I check or adjust to resolve it? Any insights or suggestions from the Alpine.js community would be greatly appreciated.


Solution

  • Livewire3 automatically loads Alpine. There are special ways to customize it. https://livewire.laravel.com/docs/installation#manually-bundling-livewire-and-alpine

    // layout blade
    
    <body>
    @livewireScriptConfig
    </body>
    
    // app.js
    
    import { Livewire, Alpine } from '../../vendor/livewire/livewire/dist/livewire.esm';
    import paginationData from './alpine/pagination-stepper.js';
    
    Alpine.data('paginationData', () => paginationData);
    
    Livewire.start()