How can you identify changes in localstorage and then trigger the activation of a new boot file or reallocate a value using Vue.js or JavaScript?

When users log in, they have the option to choose from 3 domains: dev, demo, and sandbox. The configuration for these domains is set in the Boot.js file using Axios. The boot file is triggered prior to the firing of the Vue instance. Below is the content of the boot file:

import { boot } from "quasar/wrappers";
import axios from "axios";
import { LocalStorage } from "quasar";

import { Platform } from "quasar";

let baseURL = LocalStorage.getItem("basepath");
let api = axios.create({ baseURL: baseURL });

export default boot(({ app }) => {
    // for use inside Vue files (Options API) through this.$axios and this.$api

    app.config.globalProperties.$axios = axios;
    
    app.config.globalProperties.$api = api;
});

export { axios, api }; 

The script section of the login file looks like this:

<script>
import { LocalStorage } from "quasar";

export default {
data() {
    return {
      companyList: [{
            id: "dev",
            site: "https://dev.mycompany.com",
        },
        {
            id: "demo",
            site: "https://demo.mycompany.com",
        },
        {
            id: "sandbox",
            site: "https://sandbox.mycompany.com",
        },
    ],
      loginData: {
        username: "",
        password: "",
        companyid: "",
      },
    };
  },
  methods: {
     checkCompanyId(payload) {
      let temp = this.companyList.find((o) => o.id == payload.toLowerCase());

      if (temp) {
        LocalStorage.set("basepath", temp.site); 
        return true;
      } else {
        return false;
      }
    },
     submitForm() {
        const CompanyId = this.checkCompanyId(this.loginData.companyid);

        if (CompanyId) {
           this.loginProcess(this.loginData);
         } else {
           console.log('Company ID can't be found!')
         }
      }
    },
  }   
}
</script>

The challenge arises when the value in Local Storage changes but the variable baseURL in Boot.js does not change unless the page is reloaded. Is there a way to update the baseURL variable whenever the local storage has been modified?

Answer №1

After drawing inspiration from the responses above, I took a different approach to handle my boot file which is not a vuex file. Instead of creating an action, I developed a function that can be invoked when a site is selected and then exported. Below is the implementation of the function I created to update the variable in my boot file.

let changeBasepath = (basepath) => {
    baseURL = basepath;
    api = axios.create({ baseURL: baseURL });
};

Here's how my boot file appears after incorporating the changes:

import { boot } from "quasar/wrappers";
import axios from "axios";
import { LocalStorage } from "quasar";

import { Platform } from "quasar";

let baseURL = LocalStorage.getItem("basepath");
let api = axios.create({ baseURL: baseURL });

let changeBasepath = (basepath) => {
        baseURL = basepath;
        api = axios.create({ baseURL: baseURL });
};

export default boot(({ app }) => {
    // for use inside Vue files (Options API) through this.$axios and this.$api

    app.config.globalProperties.$axios = axios;

    app.config.globalProperties.$api = api;

});

export { axios, api, changeBasepath }; 

Subsequently, I imported the updated boot file and integrated the function. The script chunk within my vue file now reflects these modifications:

<script>
import { LocalStorage } from "quasar";
import { changeBasepath } from "boot/api"; 

export default {
data() {
    return {
      companyList: [{
            id: "dev",
            site: "https://dev.mycompany.com",
        },
        {
            id: "demo",
            site: "https://demo.mycompany.com",
        },
        {
            id: "sandbox",
            site: "https://sandbox.mycompany.com",
        },
    ],
      loginData: {
        username: "",
        password: "",
        companyid: "",
      },
    };
  },
  methods: {
     checkCompanyId(payload) {
      let temp = this.companyList.find((o) => o.id == payload.toLowerCase());

      if (temp) {
        LocalStorage.set("basepath", temp.site); 
        changeBasepath(temp.site); 
        return true;
      } else {
        return false;
      }
    },
     submitForm() {
        const CompanyId = this.checkCompanyId(this.loginData.companyid);

        if (CompanyId) {
           this.loginProcess(this.loginData);
         } else {
           console.log('Company ID can't be found!')
         }
      }
    },
  }   
}
</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

Troubleshooting Type Conversion Error in ASP.NET MVC Controller

I have been working on an application that utilizes the following HTML and JavaScript. The user is required to input 5 props and then click on the 'Create' button. Subsequently, the JavaScript code compiles all of these props into a list before s ...

Conditional rendering is effective for displaying a form item based on certain conditions, but it may not be as effective for

I want a textarea element to appear or disappear based on the selected state of the radio buttons before it. If "no" is chosen, the textarea will be hidden, and if "yes" is chosen, the textarea will become visible. <fieldset class="input-group form-che ...

"Delightful Data Display: Achieving Ajax Triumph with

When I include the success function in my DataTable, the rows do not automatically fill up in the table. However, when I remove the success function everything works correctly, and the datatable fills with data as expected. I am trying to retrieve a messag ...

Using eslint with the vue plugin allows you to specify which object fields to ignore in

My ESLint rule setup includes the following: "vue/script-indent": [ "error", 4, { "baseIndent": 1, "switchCase": 1, "ignores": [ "[init.type=\"ObjectExpression\"]", "[init.type= ...

What are some ways to create a div section within a Google Map interface?

Is there a way to create a div area within the Google map iframe? Some of my code is already prepared here (). The image in this link (https://i.sstatic.net/92gkt.png) illustrates exactly what I'm trying to achieve. ...

Is it possible for npm to assist in determining the appropriate version of Primeng that is compatible with Angular 16 dependencies

While trying to add primeng to my project, I ran into an error message: npm i primeng npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to resolve dependency tree npm ERR! npm ERR! While resolving: <a href="/cdn-cgi/l/email-protection" class="__cf_email__ ...

Using Angular's $q service in the run block

I have a scenario where I need to load data from local files using the global loadJSON function (though it's not mandatory, it's recommended). Once the data is loaded from all the documents, I want to print the string 'i ve loaded'. T ...

Add three rows without clicking, then click once to add one row at a time

Seeking guidance on how to defaultly display 3 rows after adding and removing rows, as well as applying the removal of a default set of 3 rows using JavaScript. Any valuable ideas are appreciated! Example needed:- $(document).ready(function (){ ...

Is it possible to export files from Flash to CreateJS via the command line?

Is there a method to automatically run the createjs toolkit for Flash tool from the command line? I have multiple components that I need to export in bulk. Is it possible to do this in a batch process? ...

Is it possible to achieve this using an alternate method such as CSS?

Currently, I am working on a function that will apply shadow effects to all buttons within a specific class when hovered over. However, due to the dynamic nature of the buttons created based on the data retrieved from the database, assigning individual IDs ...

Making AJAX requests repeatedly within a loop

My current challenge involves implementing multiple ajax requests within a loop to populate several dropdown lists. Running the requests sequentially has resulted in only the last item in the loop being populated with values. var targetcontrols = []; ...

Instruct npm to search for the package.json within a designated directory

Imagine having a folder structure that looks like this: root |-build |-package.json |-src |-foo |-foo.csproj |-foo.cs |-bar.cs |-bin |-... |-foo.sln Now, if you change the current directory to root\src\foo\bin a ...

Retrieving information from JSON files related to table objects

How to Display JSON data in a Table? I am facing difficulty accessing my JSON data as it is nested within an array of objects. How can I retrieve this information? Currently, I am using the map function to display only the name and avatar, but the data s ...

Are you transitioning from traditional scroll pagination to using ajax?

Is it possible to replace scroll pagination with ajax? I'm looking for an alternative to the large scroll pagination query and wondering if ajax could be used instead. Here is the current code snippet: feeds.scrollFeedPagination({ 'contentPage ...

In JavaScript, creating a new array of objects by comparing two arrays of nested objects and selecting only the ones with different values

I've been struggling to make this work correctly. I have two arrays containing nested objects, arr1 and arr2. let arr1 =[{ id: 1, rideS: [ { id: 12, station: { id: 23, street: "A ...

Sorting two different divisions is an example

I need advice on how to toggle between two divs, A and B, without having to reload the page. Ideally, I would like to have three buttons - one that shows only div A when clicked, another that displays only div B, and a third button that shows both A and ...

The scripts within the body tag are failing to load

After trying to embed angular into the body tag, I noticed that nothing is loading up. Upon inspecting the resources panel, I found that only files from the head are present. Moving all the scripts to the head section resolves the issue and everything load ...

Issue with modal component triggering unexpected page reload

I'm encountering a strange issue with my modal in Vue.js. It only appears on a specific page named 'Item', but when I click on a different view, the page reloads unexpectedly. This problem seems to occur only with the route containing the mo ...

Loading asynchronous select options with a knockout observable array

I have an ajax-based asynchronous loader for select options. It accepts a remote address and returns an observable array that is correctly populated with descriptions and key values to be used in the following binding. <select data-bind="value: select ...

Transpiler failed to load

My Angular application running on Node has recently encountered a problem with the transpiler. I have been trying to load mmmagic to evaluate uploaded files, but encountered difficulties in the process. While attempting to update NPM packages, I gave up on ...