javascriptlaravelvue.jsinertiajs

Applying the page state when the user gets redirected to an already visited Page


My index method lists all users:

return Inertia::render('User/List',[
     'entries' => fn() => User::all(),
]);

The vue component to display the list has a button to create a new user.

<Button size="small" label="Add User" class="mr-5" icon="pi pi-plus" @click="$inertia.get(route('user.create'))"/>

The create method returns the inertia response with the form.

The store method also returns a Inertia response with the form. When the form is submitted, I redirect the user to the mentioned index page:

\redirect()->route('user.index')->with('successMessage', 'User created!');

How can I apply the scroll position, that the user had there? I am aware of the preserveState or preserveScroll option, but afaik this only works when reloading the current page. I am successfully using it to delete a user but maintain the scroll position, for example. The difference to the described creation process is that another page gets called.

I tried using the preserveState option while submitting the form. Surely this does not work because this preserves the state from the form, not the previously visited index page. I also tried to call the user.create route with the preserveState option, but this didnt work either.

Is there any way to redirect the user to a page while respecting the previous state of the page, like the scroll position of the page? Stuff like partial reloads only work for the visiting the same url, surely I am missing something trivial.


Solution

  • I would say you can save the scroll position on the frontend, something like this;

    const scrollPosition = window.scrollY || window.pageYOffset;
    const timestamp = Date.now();
    sessionStorage.setItem('routeIdentifierScrollPosition', JSON.stringify({
        position: scrollPosition,
        timestamp,
    }));
    

    scrollPosition is the current scroll position, and routeIdentifierScrollPosition should have the correct name of the route/view. So anytime you're redirected back to that page, you can set the user's scroll position based on the information you previously recorded. You may also want to confirm if the user was redirected from a route that the scroll position should be set back so you don't set scroll positons when it's not needed.