inertiajs / inertia-laravel

The Laravel adapter for Inertia.js.
https://inertiajs.com
MIT License
2.01k stars 224 forks source link

Router events runs multiple times. #583

Open boutzamat opened 7 months ago

boutzamat commented 7 months ago

When i'm using the Inertia Router start event, all previous events gets logged too. I'm using the following code:

router.on("start", (event) => {
    console.log(event);

    console.log(`Navigated to ${event}`);

    console.log("--------------");
});

This code is running in the main Layout, so it shouldn't be loaded more than once.

The purple box on the image is the console output when i click any link first time, the red box is when i click it the second time (i get both previous event and current event) and if i click it again it will continue like that (recursively).

Is this a bug, or am i doing it wrong?

Skærmbillede 2024-01-24 kl  14 55 17
craigrileyuk commented 6 months ago

How are you calling your layout?

It’s looks like the layout setup is running with each page load, this is to be expected if your layout isn’t persistent.

vitalijalbu commented 6 months ago

In DEV mode maybe it's ok because everything runs twice...

boutzamat commented 6 months ago

How are you calling your layout?

It’s looks like the layout setup is running with each page load, this is to be expected if your layout isn’t persistent.

This is an example of my index page that uses the Layout component: `

`

Pretty much the out of the box way of loading the DeveloperLayout. The DeveloperLayout is just the default Layout component renamed. I've tried with a fresh Laravel-Inertia installation too, and the issue is the same. The event is triggered in the DeveloperLayout component.

boutzamat commented 6 months ago

In DEV mode maybe it's ok because everything runs twice...

I just tested in production mode. The issue is the same.

craigrileyuk commented 5 months ago

Try following the instructions for Persistent Layouts instead of wrapping your layout around your page.

The way you've done it, the layout is unmounted and then re-mounted every single time you navigate. This is likely causing the event listener to be registered multiple times.