Inertia: Refresh the page with new data without altering the current scroll position

In my application using Inertia/Laravel/VueJs, I have a page displaying numerous posts where each post can be marked as completed. Upon marking a post as completed on the front-end, a CSS class should toggle to indicate completion.

The desired behavior is for a user to scroll down the page, click the completed button, and have the back-end send updated data to the front-end without causing the page to jump to the top.

Although the code below enables updating the database upon clicking the completed button, it does not reflect the new data in 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 triggered by the completed button click:

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

By modifying the Javascript function as shown below:

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

The updated data reflects on the front-end with the post marked as completed, but unfortunately, the preserveScroll feature does not function as intended, resulting in the user being redirected to the top of the page.

I'm seeking suggestions on how to achieve my desired functionality as users may have hundreds of posts, making it impractical for the page to constantly scroll to the top. Any insights would be greatly appreciated!

Answer №1

If you want to refresh your app without losing the current state, follow these steps:

 Use Inertia.get('posts', params, {
              preserveState: true,
             })

Answer №2

Approach 1: To handle your situation, all you need to do is click the "Mark as Done" button to trigger a backend request. Once you receive confirmation of a successful response, update the task on the frontend by applying a specific class to the relevant element. By following this method, you can avoid having to reload the entire DOM, as the backend process confirms that the task has been completed.

Approach 2: Implemented by big players like YouTube, Instagram, and Facebook, the strategy known as "optimistic update" is utilized for updating content in real-time. With optimistic updating, you modify your DOM immediately - like changing colors or adding classes - while waiting for the server's reply. If an error occurs during this process, the update will be rolled back automatically.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Vue warning: Issue encountered during rendering - TypeError: Attempting to access the 'id' property of an undefined variable

As I develop my CRUD application using Laravel and VueJS, I encounter an error message when submitting the creation form: [Vue warn]: Error in render: "TypeError: Cannot read property 'id' of undefined" Below is my createUser method: export def ...

Strategies for troubleshooting a blank page issue when launching a secondary Vue application with nginx

I am looking to run multiple Vue.js v3 apps with nginx on macOS Big Sur. The first app is located at: /Users/kharraz/Developer/code/homeapp/dist; And the second app is located at: /Users/kharraz/Developer/code/businessapp/dist; Both folders contain outpu ...

The Vue component fails to display the updated data even after the prop data has been modified

This is the parent component called abc.vue <v-card outlined class="mt-4"> <DetailsTable v-show="toggleClientData" :columnDefs="columnDefs" :rowData="rowData" /> </v-card> methods:{ aggridData() { let self = this; th ...

There is an issue with adding data to the database after inputting email and password for authorization in Firebase via Vue.js

The data is not being added to the database even after entering the email and password for authorization in Firebase using vue.js. When I use: firebase.auth().createUserWithEmailAndPassword(this.email, this.password) The following code does not get execu ...

Can a list be transformed into a grid layout?

disclaimer: I am currently learning vue.js and vuetify, with limited experience in javascript. This is my first attempt at creating a vue.js app. The version of vue and vuetify that I am using is 2.x. My goal is to design a scrollable list of items where ...

What are some ways to rejuvenate a computed property?

Is there a way to refresh the data displayed in someData after it has been updated and saved on the server? I have tried using $recomputed('someData'), but it's not working as expected. I believe I might need to utilize a Promise, but I&apo ...

Issue encountered when integrating vue2-google-maps into a project using vue.js and Laravel 5.6.12

I am currently utilizing Laravel 5.6.12 in combination with vue.js I am attempting to integrate Google Maps using the following GitHub link I am adhering to the instructions provided in the aforementioned link, as follows. Installation npm install vue2 ...

An exciting tutorial on creating a animated dropdown using vueJS

I've set up a navigation menu with mouseover and mouse leave events to toggle a dropdown by changing a boolean value. Now, I'm trying to apply different animations to the list items in the dropdown compared to the surrounding box, but I'm f ...

What is the best way to create a list from a matrix using JavaScript?

I have an array structured as follows: const input_array= [ ["red", "green"], ["small", "medium"], ["x", "y", "z"] //... can have any number of rows added dynamically ...

Tips on how to trigger the function upon receiving the response value by concurrently running two asynchronous functions

export default { data: () =>({ data1: [], data2: [], lastData: [] }), mounted() { asynchronous1(val, (data)=>{ return this.data1 = data }) asynchronous2(val, (data)=>{ return this.data2 = data }) f ...

I am facing an issue with the routing functionality in the Quasar framework for Vue 3

I seem to be having an issue with my code where no matter what route I give, it only takes me to the home page. Specifically, when I give the path "auth", it still redirects me to the home page. Can someone please help me understand why this is happening a ...

Adding an event listener dynamically in NativeScript-Vue programmatically

For my debut app project with NativeScript Vue, I'm encountering a hurdle. How can I programmatically set an event listener to a component? In a typical Vue application, you would utilize the syntax: component.$on('eventName', eventHandler), ...

Creating reactive Arrays in VueJSIn this guide, we will discuss methods

Struggling to implement a hover effect on images with Vue, specifically aiming to display the second item in an image array upon hover. The challenge is maintaining updated data in the templates when changes occur. Even attempted using Computed properties ...

Ways to prevent event bubbling in the case of a checkbox input alteration?

Description I am looking to create a table component with checkboxes, but I am facing an issue. Whenever I click on a checkbox, the click event is also triggered for the table row and cell containing the checkbox, which is not what I want. I have tried us ...

Tips for invoking the controller's update method

I have been encountering an issue while attempting to utilize the update function of my controller on the dashboard.blade.php page. Upon clicking "Save", instead of updating, the page switches to show.blade.php. Content of my dashboard.blade.php: ...

Can I pass a variable to the data() option of a Vue composition API component?

After defining a variable in the setup function: setup(props, context) { let name = "Tommy"; } How can this variable be accessed and used within the component? data() { return { myName: name } }, The variable is accessib ...

Using media queries in VueJS style tags may not have the desired effect

I've encountered an issue with using @media in the style tags of a VueJS component. Surprisingly, styling within the @media query works consistently, while applying styles based on width rules does not seem to have any effect. <template> &l ...

Deleting associated records in LaravelLaravel gives you the ability

Managing soft deletion of departments when a company is soft deleted can be tricky. The current implementation involves iterating through each department associated with the company and soft deleting them. However, it seems that only the first department i ...

Having trouble with Vuejs uploading multiple images when not using a CDN?

Hello! I am currently experimenting with implementing this specific plugin for uploading multiple images using vue.js. Below you can find the code snippet that I have been working on. <!DOCTYPE html> <html lang="en> <head> &l ...

Leveraging pre-rendered HTML in Vue.js components for both parent and child elements

Currently, I am rendering all the HTML server-side and attempting to use Vue to set this HTML as the $el for two components. According to the lifecycle diagram, this should be possible. There is a parent Vue instance (which binds to #main) that contains a ...