Revert the Vue State When Navigating Back in the Browser

Background

In our checkout process, we redirect to Stripe after creating an order object through an API request. To prevent users from clicking the "checkout" button multiple times during this process, we toggle a variable value to show a loading icon when the button is clicked.

Our application is built in Laravel with Jetstream (using Inertia), which limits our ability to reset values on form success due to how Inertia works.

Issue

Everything works as intended until a user clicks the browser back button after being redirected to Stripe. At that point, the loading icon remains visible because Vue does not reset the state of the variable to false.

<template>
   <div>
      <div v-if="loadingCheckout">Loading</div>
      <button v-if="!loadingCheckout" @click="startPurchase">Checkout</button>
   </div>
</template>
<script>
   import { defineComponent, ref } from 'vue'
   export default defineComponent({
      data() {
        return {
            loadingCheckout: false,
        };
       },
       methods: {
        startPurchase() {
            this.loadingCheckout = true;
            // Create checkout logic
        }
       }
   })
</script>

Possible Solutions

We have attempted to use event resets like setUp, beforeMount, and mounted without success. Trying a ref inside setup instead of the data approach yielded the same issue.

Other attempts include generating the data property using a method, utilizing Inertia callbacks such as onSuccess (which didn't trigger properly due to JetStream), but none of these approaches resolved the issue.

We need ideas to ensure that the state is only applied during each page render and not stored in memory. This problem seems to be related to Inertia/Vue storing the state in the browser history.

Answer №1

In order to find a solution, I made the switch from utilizing the Inertia form methods and opted for the form helper methods instead , which had functional callbacks.

By replacing

this.$inertia.post(route('purchase.store'));

with

this.$inertia.form().post(route('purchase.store'), {
    onFinish: () => this.loadingCheckout = false,
})

The updated version of my code is as follows:

<template>
   <div>
      <div v-if="loadingCheckout">Loading</div>
      <button v-if="!loadingCheckout" @click="startPurchase">Checkout</button>
   </div>
</template>
<script>
   import { defineComponent, ref } from 'vue'
   export default defineComponent({
      data() {
        return {
            loadingCheckout: false,
        };
       },
       methods: {
        startPurchase() {
            this.loadingCheckout = true;
            // Implement checkout process
            
            this.$inertia.form().post(route('purchase.store'), {
                preserveScroll: true,
                onFinish: () => this.loadingCheckout = false,
            })
        }
       }
   })
</script>

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

The jQuery script operates just one time

Recently, I encountered a small issue with my script. It only seems to work once - after that, I have to refresh the page in order to remove a favorite article (which the script is supposed to do). $("a.fav_no").on('click', function () { ...

Tips for displaying just the image name without the entire image file path

When I try to upload an image, the path displayed is "C:\fakepath\promotion1.JPG". This fake path is causing the image not to upload to my project media folder. How can I solve this issue? Instead of the complete path, I only want to capture the ...

Google Chrome does not support inlined sources when it comes to source maps

Greetings to all who venture across the vast expanse of the internet! I am currently delving into the realm of typescript-code and transcending it into javascript. With the utilization of both --inlineSourceMap and --inlineSources flags, I have observed t ...

Using JQuery, retain only the initial N elements in a list and discard the rest

I'm looking to streamline a list of items in the DOM by keeping only the first N items, ideally through the use of slice and remove methods. Could someone provide me with the JQuery syntax for removing items that come after the first N in the list? ...

Creating a fade in or fade out effect in AJAX without using jQuery is a simple yet

Is there a simple way to achieve fade in or fade out effects in ajax without relying on jQuery? I'm looking for a solution that can add color or background color to make it visually appealing, especially for small web pages with poor internet connecti ...

A step-by-step guide to creating a delete feature for nested data in Laravel using Vue.js

My standard function format for deleting is not working on nested data. methods: { delete() { axios.delete('./../api/parent/' + this.parent.id) .then( response => { if( re ...

The error message "no match found" can only occur on the server-side when using jQuery version 1.x

Having an issue with this small section of code: $('.desc_container').each(function() { var fulltext = $(this).text(); if(fulltext.length > 50) { var myRegexp = /^(.{47}\w*\W)(.*?)$/g; var match = myRegexp.exec(f ...

What is the best way to assign unique IDs to automatically generated buttons in Angular?

Displayed below is a snippet of source code from an IONIC page dedicated to shapes and their information. Each shape on the page has two buttons associated with it: shape-properties-button and material-information-button. Is it possible to assign different ...

Implementing automatic value setting for Material UI slider - a complete guide

I am working on developing a slider that can automatically update its displayed value at regular intervals. Similar to the playback timeline feature found on platforms like Spotify, Soundcloud, or YouTube. However, I still want the slider to be interactive ...

Synced Slideshows

Currently experimenting with the Owl Carousel plugin to create multiple synced carousels using their demo at the link below. However, I'm facing a specific issue when dealing with different numbers of small items in each carousel. I've successfu ...

What could be causing the recurring appearance of the success alert message in an AJAX call to a PHP script in this particular situation?

Below you will find two code blocks, each designed to handle an AJAX call to a PHP file upon clicking on a specific hyperlink: <script language="javascript" type="text/javascript"> $(".fixed").click(function(e) { var action_url1 = $(th ...

Having trouble establishing a new local Windows directory structure with Selenium

After following the guidelines provided here and here, I am striving to ensure that the directory where my results reports are stored is consistently available for each user. new File(sampleFolder).mkdir(); The sampleFolder path displayed in the Eclipse ...

Implementing diverse color gradients to individual vertices within a geometry using three.js

My goal is to enhance the functionality of this code snippet so that when the button is clicked, the selected mesh's neighborhood vertex is highlighted with a gradient effect. function addSphere() { var position = new Array(); var notAboveGround = tr ...

Integrating dynamic transition effects using Jquery Mobile for <div> elements

Just a friendly reminder, I must admit that my knowledge of Javascript is quite limited. I received a script from Padilicious to implement swipe navigation on my Jquery Mobile Site. It involves adding functions to a div tag like this: <div data-ro ...

A Guide to Effortlessly Implementing moment.js into a React TypeScript Application

I'm attempting to implement code splitting and one of the specific packages I want to separate into its own chunk is moment.js. Here's how I'm doing it: const myFunc = async (currentNumber) => { const moment = (await import('momen ...

Having difficulty displaying Laravel API data with Relationship in Vue Js

Working on a project that involves Laravel 10 API and Vue.js 3 frontend In my EmployeeController.php file, I have three models: Employee, Title, and Salary. The Employee model has a many-to-many relationship with the Salary and Title models, while the Sal ...

Guide to making a request in Node.js to Amazon S3 for downloading a specific file

Recently, I encountered an issue while trying to download a file from Amazon S3 using Node.js. Upon receiving the response, I noticed that there were 2 problems with the Buffer data: When I tried sending the buffer from Node.js to the frontend using res ...

Tips on resolving issues with cellclickable functionality in Angular with gridster2

VERSION: ^9.3.3 HTML <button (click)="toggleEditing()">{ editing ? 'cancel' : 'editing' }</button> <button>ADD</button> <gridster [options]="options"> &l ...

Dealing with the Windows authentication popup in Protractor

I recently started using Protractor and encountered a problem with managing the authentication popup. I have included a screenshot for reference. If anyone has a solution, please advise me on how to resolve this issue. Thank you in advance. ...

Retrieve the information transmitted to an EJS file within a separately included JavaScript file

I'm currently utilizing express js to render a file by using: res.render('plain',{state:'admin'}) The file plain.ejs includes main.js: <script src ="/main.js"></script> I need assistance on how to access the state v ...