When dealing with JavaScript Single Page applications, such as Vue.js, and you have a form with a lengthy submit action (like saving something), it is crucial to handle the scenario where the user navigates away before the operation completes. In this case, the submit action should save the data and then redirect to a new route for a success message.
If the user navigates to a different link while waiting for the result, it can cause issues.
Take a look at this fiddle:
https://jsfiddle.net/hajbgt28/4/
const Home = {
template: '<div><button @click="submit">Save and go Bar!</button></div>',
methods: {
async submit() {
await setTimeout(() => {
this.$router.push("/bar");
}, 5000);
}
}
};
const Foo = { template: '<div>Foo</div>' }
const Bar = { template: '<div>Bar</div>' }
const router = new VueRouter({
mode: 'history',
routes: [
{ path: '/', component: Home },
{ path: '/foo', component: Foo },
{ path: '/bar', component: Bar }
]
})
new Vue({
router,
el: '#app',
data: {
msg: 'Hello World'
}
})
- Click Home
- Click the button
- Click on "Foo" immediately, you see "Foo"
- Wait a few seconds
- The Page changes to "Bar"
Two solutions come to mind:
- Incorporate logic in the submit operation to check if the user is still on the intended route before proceeding. However, this approach can become complex.
- Disable all links on the page during loading to prevent users from navigating away. But this can hinder the usability of the page until the operation finishes.
What would be considered best practice for handling situations like this?