inertia-laravel icon indicating copy to clipboard operation
inertia-laravel copied to clipboard

Router events runs multiple times.

Open boutzamat opened this issue 1 year ago • 5 comments

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

boutzamat avatar Jan 24 '24 14:01 boutzamat

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.

craigrileyuk avatar Jan 25 '24 23:01 craigrileyuk

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

vitalijalbu avatar Jan 26 '24 07:01 vitalijalbu

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: `

const props = usePage().props;

`

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 avatar Jan 26 '24 11:01 boutzamat

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

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

boutzamat avatar Jan 26 '24 11:01 boutzamat

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.

craigrileyuk avatar Mar 11 '24 00:03 craigrileyuk