Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inertia: Reload page with updated data without modifying scroll position

I'm using Inertia/Laravel/VueJs. I have a page with many posts and each post can be marked as completed. When a post is marked as completed on the front-end I have a v-bind which toggles a CSS class which should be applied to completed tasks.

The behaviour I would like is: a user scrolls down a page, clicks the completed button, and the back-end sends that newly updated data to the front-end, making the v-bind true, causing the CSS class to be applied without jumping to the top of the page.

With the code below I can click the completed button, and it is updated in the database, but that new data isn't sent to the front-end.

Controller:

    public function markAsCompleted(Request $request)
    {
        $post = Post::find($request->id);

        $post->completed = true;

        $post->save();

        return Redirect::route('posts');
    }

Javascript function called at click of completed button:

completed(id) {
   this.completedForm.put(`/endpoint/completed/${id}`, {
      preserveScroll: true
   });
},

If I change the Javascript function to:

            completed(id) {
                this.completedForm.put(`/endpoint/completed/${id}`, {
                    preserveScroll: true,
                    onSuccess: () => {
                        Inertia.get('posts');
                    },
                });
            },

In this case, the new data is returned to the front-end with the post being marked as completed, but the preserveScroll doesn't work, and jumps the user to the top of the page.

Any ideas on how to get my desired use case working? Users could have hundreds of posts so I can't have the page jump up to the top every time.

Thank you for any help!

like image 251
vue-coder Avatar asked Sep 01 '25 04:09

vue-coder


2 Answers

To update your app while preserving the state:

 Inertia.get('posts', params, {
              preserveState: true,
             })
like image 66
Tim Kariuki Avatar answered Sep 03 '25 12:09

Tim Kariuki


Option 1: In your scenario, simply click the "Completed" button to send a request to the backend. After confirming a successful response, update the task in the frontend as complete by adding a class to the corresponding element. This approach avoids the need to re-render the entire DOM, as a successful response ensures the backend task is completed.

Option 2: This approach is known as "optimistic update," which is widely employed by major websites such as YouTube, Instagram, and Facebook for content updates. With optimistic updating, you make immediate changes to your DOM, such as adding a class or altering colors, while awaiting the server response. If an error occurs, the update is canceled.

like image 21
Miro Grujin Avatar answered Sep 03 '25 13:09

Miro Grujin