Why does the Vue router sometimes refresh the page instead of properly navigating to it? Can you spot the difference between these two code examples?

I am encountering an issue while trying to click on a "checkout" button that is supposed to send cart data to a backend and redirect me to a URL generated by the backend.

Despite receiving a valid URL, my code is not functioning correctly. When I attempt to redirect to the provided URL, the page simply refreshes without redirecting me anywhere.

Although I have a working version of the code from a different project, my attempts to replicate it by copying and pasting have been unsuccessful. Refactoring it to align with my current codebase has also proven to be a challenge, as I cannot seem to identify the necessary adjustments to make it operational.


The code snippet above represents the working code, while the one below it is my non-functional code. I am seeking assistance to understand the disparity between the two sets of code. What is causing the malfunction in my version? How can I modify it to mirror the functionality of the working code?

Working

-Frontend

<script setup>
import { ref, onBeforeMount } from "vue";
import CheckoutSummary from "../components/CheckoutSummary.vue";
import CheckoutButton from "../components/CheckoutButton.vue";

// Reactive data
const isLoading = ref(false);
const cart = ref([]);

// Get the cart data
onBeforeMount(async () => {
  const response = await fetch("/api/shopping-cart").then((r) => r.json());
  cart.value = response.cart;
});

// Click handler for button
const redirectToStripe = async () => {
  isLoading.value = true;

  const response = await fetch("/api/create-checkout-session", {
    method: "POST",
  });
  const { url } = await response.json();

  window.location.href = url;
};
</script>

-Backend

// Create a Checkout Session
app.post("/create-checkout-session", async (req, res) => {
  // Make an array of just our Stripe Price ID and quantities
  const lineItems = USER_SHOPPING_CART.map((item) => {
    return {
      price: item.stripePriceId,
      quantity: item.quantity,
    };
  });

  const session = await stripe.checkout.sessions.create({
    mode: "payment",
    line_items: lineItems,
    success_url: `http://localhost:3000/success?session_id={CHECKOUT_SESSION_ID}`,
    cancel_url: `http://localhost:3000/`,
  });
  return res.send({ url: session.url });
});

Not Working

-Frontend

<script setup>
import { computed } from "vue";
import { useRouter } from "vue-router";
import { useStore } from "vuex";

const router = useRouter();

// eslint-disable-next-line no-unused-vars, no-undef
const props = defineProps({
  isLoading: Boolean,
});

const store = useStore();
const cartItems = computed(() => store.getters.getCheckout);

const redirectToStripe = async () => {
  const { url } = await fetch("http://localhost:5000/create-checkout-session", {
    method: "POST",
    headers: {
      Accept: "application/json",
      "Content-Type": "application/json",
    },
    body: JSON.stringify(cartItems.value),
  }).then((response) => response.json());

  console.log("url=", url);
  router.go(url);
};
</script>

-Backend

app.post("/create-checkout-session", async (req, res) => {
  // Make an array of just our Stripe Price ID and quantities
  const lineItems = req.body.map((item) => {
    console.log("lineItems= ", item.item.priceId, item.item.quantity);
    return {
      price: item.item.priceId,
      quantity: item.item.quantity,
    };
  });

  const session = await stripe.checkout.sessions.create({
    mode: "payment",
    line_items: lineItems,
    success_url: `http://localhost:8080/success?session_id={CHECKOUT_SESSION_ID}`,
    cancel_url: `http://localhost:8080/`,
  });
  return res.send({ url: session.url });
});

Answer №1

Incorporate router.push(url) in place of router.go(url)

While utilizing Vue router, it is advisable to opt for router.push for navigation rather than resorting to location.href since the latter may lead to unforeseen outcomes.

Answer №2

router.go is a function that allows you to move forward or backward by a specified number of pages in your browsing history.

router.push is used to navigate to a different page within your application by adding a new entry to the browser history. It is ideal for transitioning between pages on the same website, such as moving from '/about' to '/careers'.

If you need to redirect to a completely different page, consider using window.open to open the page in a new window.

For links to checkout pages, it may be preferable to open them in a new tab using window.open(url, '_blank').

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

how to use jQuery to hide a flash-containing div without losing its content

Hello, I created a modal with jQuery UI that is displaying in front of a flash movie. However, the HTML content inside the modal appears corrupted. I attempted to hide the movie just before the modal is triggered and make it reappear after closing the mo ...

Utilize the lodash times method for indexing

I have a requirement to duplicate a component "n" number of times. I achieved this by utilizing the lodash method called "times". However, I encountered an issue with assigning an index as a key for the generated components. Below is the snippet of code t ...

Tips to swap selections in a Select2 dropdown box

Is there a way to dynamically clear a Select2 option list and reload it with new data? Despite setting the data as suggested, it seems to only append the new data without clearing the existing options. $("#optioner").select2(); $("#doit").click(functio ...

Is Socket.io exclusive to browsers?

Similar Question: Using socket.io standalone without node.js How to run socket.io (client side only) on apache server My website is hosted on a Linux server with shared hosting. Since I don't have the ability to install node.js, I am looking ...

Assigning an argument of type `any` to a parameter of type `Observable<IComboboxItem[]>` can be considered risky

I have a piece of code that retrieves data from the backend server. Here is the code snippet: @Injectable() export class DictionariesDatasourceFacadeService { public invoiceTemplate: IDataSource<IComboboxItem>; public replacedLegalEntity: IData ...

The error message "MediaMetadata is not defined as no-undef and cannot be used as a constructor" appeared when trying to use MediaMetadata

I have successfully implemented a playlist player using howler.js in vuejs. Now, I am looking to enhance it by integrating the MediaMetadata API. While the MediaSession API is functioning well with controls like notification bar, keyboard controls, and rem ...

Utilize the native plugins within your Nativescript Vue application

Currently, I am facing some challenges with integrating plugins into my application. Despite successfully installing plugins using npm and seeing them added to package.json and package-lock.json files, I am unsure of how to effectively incorporate them. Fo ...

What is the best way to display all MongoDb records when there is no query specified?

Seeking advice on modifying an endpoint that currently fetches all courses from the database by default. I am looking to update it so that when req.query.class is empty, it retrieves all records, otherwise returns records conditionally. router.get('/a ...

What causes the React Query cache to be cleared upon page reload?

Hi there, I am new to Next.js and React Query. I would really appreciate any help or advice. I apologize for any mistakes in my English language skills. Currently, I am using Next.js v12 and React Query v3, along with the React Query DevTools. On one of ...

Having trouble displaying a popup dialog box in ASP.NET using JavaScript

I am trying to implement a popup dialog box in ASP.NET using JavaScript, but it's not working as expected! Below is the code I am using: <button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal">Open Modal< ...

Styler column - Bootstrap-vue - VueJS

The goal is to format the 'from' and 'to' columns in a way that displays their description rather than their code in the table. <b-table id="my-table" hover striped small outlined :items="items" :fields="fields" class="mt-0 mb-0"> ...

An issue encountered with res.download() following res.render() in Node.js

Just started working with Node JS and ran into an issue: Error: Can't set headers after they are sent. I've checked my code, and the problem seems to be related to res.download(); Is there a way to display the view without using res.render()? ...

Issues with IIS Node and Windows Authentication: Continuous Prompt for Credentials on IIS Website

I am encountering an issue with my IIS Website that is running on localhost:3000 using NodeJS, Express, passport, and passport-windowsauth. Despite entering the correct credentials, the URL keeps prompting for user credentials repeatedly. This problem has ...

What is the best way to handle parsing JSON with special characters in JavaScript?

Content stored in my database: "Recommended cutting conditions" When using Json_encode in PHP, the result is: {"table1":[{"Item":{"original_text":"\u63a8\u5968\u5207\u524a\u6761\u4ef6 \b"}}]}; In JavaScript : var str ...

Ways to style a div element in CSS to achieve a unique shape

Hello there! I'm looking to achieve a tilted background div effect. Anyone have any tips or ideas on how I can do this? I'm new to web development and would appreciate the guidance. https://i.stack.imgur.com/wyj1X.png ...

Link that causes the regular expression test to hang

My goal is to create a regular expression that can accurately identify URLs. I found the code snippet for this on Check if a Javascript string is a url. The code looks like this: function ValidURL(str) { var pattern = new RegExp('^(https?:\/&b ...

I am still receiving an empty dropdown value despite implementing ng-selected

I am having issues with using ng-selected to retrieve the selected value from a dropdown. Instead of displaying the selected value, it appears blank. Here is the code snippet I have tried: <div> <select id="user_org" ng-model="selectedorg.all ...

Guide to forming an array by extracting specific properties from a nested JSON array using javascript

Currently, I have this list: list = { id: 1, arr: [ {index : 1 , description: "lol" , author: "Arthur"}, {index : 2 , description: "sdadsa" , author: "Bob"}, {index : 3 , desc ...

Saving real-time information to MongoDB with Node.js

What is the best way to use JSON.stringify and send it to my mongoDB Database? For instance: import express from 'express'; let data_record = JSON.stringify({**any content**}) This snippet of code will automatically fetch data every 60 second ...

Should the ListItem expand and collapse when clicked?

My react/material-ui component has the following structure: export const TodoItem: React.FC<Props> = ( {todo, itemKey}) => { const [dialogState, setDialogState] = React.useState<boolean>(false); const handleClose = () => { setDial ...