Issue with using reload=true in @click function not functioning

I have been working on implementing a currency switcher feature. I am trying to call a method when clicking the link and once the method is successfully executed, I want it to reload automatically. However, the automatic reload functionality does not seem to be working. The currency gets stored in a cookie, and refreshing the page manually updates it in the navbar as expected. But ideally, I would like it to reload automatically once the method completes.

Here is the code snippet from the navbar:

<b-dropdown position="is-bottom-left" aria-role="menu">
  <template #trigger>
    <a class="navbar-item font-bold" role="button">
      {{currency}}
      <b-icon icon="menu-down"></b-icon>
    </a>
  </template>
  <b-dropdown-item v-for="(item, index) in currencies" :key="index" has-link aria-role="menuitem">
    <a class="no-underline" @click="setCurrency(item.iso, (reload = true))"><span class="text-pink-600 font-bold">{{item.fullname}} ({{item.iso}})</span></a>
  </b-dropdown-item>
</b-dropdown>

This is the method being used:

methods: {
  setCurrency(newcurrency) {
    this.$cookies.set(`usercurrency`, newcurrency, {
      path: '/',
      maxAge: 60 * 60 * 24 * 7
    })
  // window.location.href = '/'
  }
}

I initially considered using window.location.href = '/' after setting the cookie, but encountered issues because the same method is used in the created hook to set the currency based on the user's country, resulting in a "window not defined" error. Here is the related code snippet:

created() {
  const isCurrency = this.$cookies.get('usercurrency')
  const isUserCountry = this.$cookies.get('usercountry')
  if (isCurrency === undefined) {
    if (isUserCountry === undefined) {
      fetch('https://ipinfo.io/json?token=*********')
        .then((response) => response.json())
        .then((jsonResponse) => {
          const country = jsonResponse.country
          this.$cookies.set(`usercountry`, country, {
            path: '/',
            maxAge: 60 * 60 * 24 * 7,
          })
          var CurrencyParam
          switch (country) {
            case 'IN':
            case 'NP':
              CurrencyParam = 'INR'
              break
            case 'US':
              CurrencyParam = 'USD'
              break
            // more cases...
            default:
              CurrencyParam = 'USD'
          }
          this.setCurrency(CurrencyParam)
        })
        .catch((error) => {
          console.log(error)
          this.setCurrency('USD')
        })
    }
  }
},

Answer №1

One easy fix could involve including a parameter called reload in the setCurrency function.

methods: {
    setCurrency(newVal, reload) {
        this.$cookies.set(`usercurrency`, newVal, {
            path: '/',
            maxAge: 60 * 60 * 24 * 7
        })
        if (reload) window.location.href = '/'
    }
}

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

Is there an error thrown when a JavaScript function is executed in the following pattern: "xyz()()"?

let calculateSum = function() { console.log(arguments.length); } calculateSum(1)(2)(3); Can anyone help with resolving the "not a function" error being thrown by this script? I am running it in NodeJs environment. ...

Combine all parameters into a single parameter, called 'useParams', displaying all values

While creating breadcrumbs that utilize navigate logic (navigate(-1)), I am running into an issue where the breadcrumbs need to exclude any URL parameters. My routes are constructed with various service providers. For instance, the '/' route con ...

After installing babylonjs via npm, encountering the error 'Unable to utilize import statement outside a module'

Recently, I've been working on setting up babylonjs through npm. Starting with a new project, I ran npm init and then proceeded to install babylonjs using npm install babylonjs --save, following the provided documentation. I then created a JavaScript ...

Modify the color of a div after selecting an li element

Can you please provide your expertise and assistance once again? I am attempting to create a function where the background color of the main div changes every time a user clicks on a list item below. Please note that there can be more than two items in the ...

The message that keeps popping up says "TypeError: Unable to access the 'execute' property of an undefined object."

I am currently working on creating a Discord bot and encountering an error that says "TypeError: Cannot read property 'execute' undefined". Despite trying multiple solutions, I am still facing some issues with my code. Any help in solving this pr ...

What is the rationale behind jQuery.each not using Array.forEach when it is accessible?

After delving deep into the codebase of the underscore library, I came across an interesting discovery. It seems that _.each relies on an ECMAScript 5 API called Array.forEach whenever it is available: var each = _.each = _.forEach = function(obj, iterato ...

Using V-for to loop through a list of items, with a unique twist thrown in

I've successfully used v-for to display an array in a single line, but I want to add commas between each word. The issue is that adding a comma at the end results in an extra comma. Any ideas on how to tackle this? ...

C# GridView using a modal popup

Currently, I am working on incorporating a lightbox into a gridview. The lightbox I have chosen to use can be found here on Particle Tree's website Essentially, in order to make the lightbox function correctly, you need to include a css and rel attr ...

The rejection of the WordPress custom plugin was due to the use of the reason 'Directly accessing core loading files'

I created a plugin for personal use and later decided to make it available to the public. However, my submission was rejected after a code review citing the reason ##Calling core loading files directly. I have addressed all the issues pointed out, except ...

The Mongoose function findbyIdAndRemove is currently not working properly when triggered on the client-side

I have a specific route in my app that uses the mongoose method findByIdAndRemove. Strangely, when I test this route using postman, it successfully deletes documents from my database. However, when I try to call this method from my client-side JavaScript f ...

JavaScript allows for the dynamic addition of foreign objects to an SVG

After running this code initially, it displays a blank screen, but when I make updates using the developer tool in Chrome, the data appears. Can someone provide an explanation as to why this happens? Could it be related to the DOM running again in the br ...

The div inside an iframe is not displaying the desired background color as intended from the parent page

The code snippet below is included in the <head> section of the main page: <script type="text/javascript"> $(document).ready(function () { $('#innerframe').load(function () { $(this).contents().find($(".TitleB ...

Struggling to retrieve JSON data from within an array

[ { "May": [ { "year": 1994, "date": "2" }, { "Sequence": 2, "Type": "Images" } ], "_id": "1122" } ] The issue I am facing is retrieving the id except for the "date" f ...

`How to show several div elements with a single click using Angular.js`

My code snippet is structured as follows: <div ng-controller="ClientCtrl"> <div ng-show="shows">hello</div> <div ng-show="show">world</div> <button ng-click="show=!show">click</button> ...

Tips for resetting the camera position on a canvas

Seeking advice on adjusting the camera position in my code. Any suggestions? I have played around with camera.position.set and added parameters for camera.position.x. function main() { const canvas = document.querySelector('#c'); const rend ...

Adapting the visible outcome based on the second figure of a numerical value

Is there a way to automatically change the displayed value using a Vue filter when the last digit of the value falls within a specific range, such as 2-4? I am looking for a solution that can work for all possible intervals like (22-24, 32-34, 622-624... ...

Verify the security of form authentication on the client-side

For my ASP.NET website, I am utilizing Form Authentication and need to verify the user's authentication status before initiating a callback on the client-side. What is the best way to accomplish this using JavaScript/jQuery? ...

Inspect the variable in JavaScript and then increment it by one every second

I am facing an issue where I need to check a variable. If it's 0, then I need to increment it after 1.5 seconds. If it's 10, then I need to increment it after 0.4 seconds. It's quite complex and the current code implementation is not working ...

adjusting array based on screen size fluctuations

Imagine having two arrays of images named landscape_images[] and portrait_images[]. One is for the landscape view and the other for the portrait view. When the screen width is in landscape mode, the wide resolution images will be displayed on the body. C ...

Tips for sending an array of objects to Node.js and ultimately storing it in a MongoDB document

Previously, I was able to send individual objects to a nodejs server using req.body.object. However, I'm encountering an issue when trying to send an array of objects to a mongo document using req.body.array. On my front end, I have successfully save ...