How can you correctly make an Ajax request using computed properties sourced from VueX Store?

Is there a way to make an AJAX call where one of the parameters is a computed State in VueX? For instance, if I use this.$axios.get('someUrl/' + accID ), with accID being a computed property from VueX (using MapState), sometimes it returns 'undefined'. I suspect this is because axios is making the get request before the id data is populated from the store.

I have attempted to use watch() on 'accID' in the Vue component to wait until accID resolves, but it hasn't been successful.

//some partial code

 computed: {
    ...mapState(['user']),
  },

 async fetchData() {

        const [foodData, option] = await Promise.all([
          this.$axios({
            url: `food/${this.user.accID}`,
            method: 'get',
          }),
          this.$axios({
            url: 'options',
            method: 'get',
          })
        ])

  //foodData returns undefined because user.accID is undefined (sometimes)

Expected Output:

this.$axios({ url:'food/12345', method: 'get' })

Actual Output:

this.$axios({ url:'food/undefined', method: 'get' })

Answer №1

Replace ${user.accID} with ${this.user.accID} within the url variable:

url: `food/${this.user.accID}`,

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

Maintaining awareness of which accordion drawer is currently open within a React application

Just getting started with coding, I recently created a collapsible accordion in a NextJs app using the react-collapse package. Everything seems to be working fine, but I'm running into an issue with keeping track of which 'drawer' is current ...

What is the best way to link the value of a mat-slider to an input field in a reactive form?

Is there a way to synchronize the min and max values of a ranged mat-slider with corresponding input fields? Currently, when I set numbers in the input fields, the slider updates correctly. However, when I use the slider to change the value of the input fi ...

Using Tinymce to automatically send form on blur action

Attempting to trigger form submission upon blur event in Tinymce, but encountering difficulties. tinymce.init({ selector: 'textarea.html', menubar:false, force_br_newlines : true, force_p_newlines ...

What is the best way to insert a variable into a nested component in Vue.js?

I am currently working on an app that has nested components. The app is triggered by the filter id. Within the app, there is a data element called minTotalSpent which is currently set to "3". The first placement on the page is displaying correctly. Howev ...

What could be causing the issue with my dynamic sitemap.xml file not functioning properly?

I have encountered an issue with creating a dynamic sitemap in my Next.js app. Despite following the instructions in the Next.js documentation and placing a sitemap.js file inside my app directory, I am seeing a 404 error when trying to access http://local ...

What is the process for placing API routes within the new app directory of Next.js?

If you have a test API located at: pages\api\accounts\login.js, and are currently exploring the new app folder, which is still in its experimental phase in Next.js (as of today). Are you wondering if it's feasible to transfer your logi ...

Tips for arranging Intervals in sequence?

I've been developing a customized Pomodoro timer with user-defined work and rest times. In my Timer component, I have the following initial logic: useEffect(() => { start(3); start(timeData.workTime); start(timeData.restTime); }, []) c ...

AngularJS substitution with regular expressions

Looking to replace specific words in HTML content within <div> and <p> tags upon page load. Utilizing angularJS to achieve this task. This is my current function: var elementsList = e.find('p'); var regex = ('[^<>\& ...

Configuring Vuex State

Currently, I have a prop that is being bound to a child component. My goal is to eliminate this binding and instead assign the value to a data property in a vuex global state. <VideoPip :asset="asset" v-show="pipEnabled === true" /&g ...

Enhancing Kendo Grid with Checkbox Columns

I am facing a situation with my kendo grid where I need to insert two checkbox columns in addition to the existing set of columns. <script id="sectionPage" type="text/kendo-tmpl"> @(Html.Kendo().Grid<SectionPageModel>() .Na ...

What is the best way to instantly update $scope when working with non-angular code?

Working with a non-angular library requires establishing communication between them. <div id="MoipWidget" data-token="{{personaltoken}}" callback-method-success="successCB" callback-method-error="errorCB"></div> Upon page load, a token must b ...

The element is currently unavailable as it has not been displayed on the screen. How can we effectively wait for its rendering

Within my Vue application, there is an image element with a bound src attribute located in a stepper. The user selects an image to upload in one step, and in the next step, the chosen image is displayed (which functions correctly). However, when attempting ...

A step-by-step guide on integrating HTML form input with an API object array

I'm looking to combine two code "snippets" but I'm not sure how to do it. One part of the code turns HTML form input into a JSON object. You can see the CodePen example here. What I want is when the "Add note" button is clicked, I want to grab ...

send document through ajax

Having some trouble with this task. Here is what I've managed to put together so far: <input id="newFile" type="file"/> <span style="background-color:orange;" onClick="newImage()">HEYTRY</span> I know it's not much progress. ...

Emphasize rows in the MUI-Datatables framework

A table was created using React.js and MUI-Datatables: import MUIDataTable from "mui-datatables"; const columns = ["Name", "Company", "City", "State"]; const data = [ ["Joe James", "Test Corp", "Yonkers", "NY"], ["John Walsh", "Test Corp", "Hartford", ...

Here is a unique version of the text: "Implementing a JavaScript function in Angular to activate the data-bs

Attempting to use JavaScript in angular to close/hide a bootstrap5 modal, encountering an issue where the hide function in bootstrap is not working. When manually clicking a button with data-bs-dismiss attribute, it closes the modal as expected, but when t ...

What is the importance of using the :key attribute on a child component element?

Examining the code snippet below, component2 employs binding on :key. When the button handleClickComp2 is clicked, the bound value on :key increments, causing component2 to be unmounted and then remounted, as shown in the console logs of the screenshot att ...

Prevent background music from being manipulated

I've implemented an audio HTML element with background music for a game: <audio class="music" src="..." loop></audio> However, I have encountered an issue where upon loading the page, I am able to control the music usi ...

Is it possible to continuously divide or multiply numbers by 2 without encountering any rounding errors when working with floating point numbers?

binary can only represent those numbers as a finite fraction where the denominator is a power of 2 Are calculations done in binary/floating point format still accurate, even after multiple additions or multiplications by 2 without any rounding errors? co ...

What is the best way to initialize a JavaScript constructor in AngularJS, similar to using ng-init to define variables but calling the constructor in service.js?

I need help converting this code to AngularJS. The current code is in core JavaScript and I want to call a core JavaScript constructor from AngularJS. I have successfully defined how to call the service constructor in core, but I am unsure of how to call i ...