Sharing data across Vue methods

I have a method that makes two API calls and saves the results in separate variables. I need to access these variables from another method to manipulate the data.

What is the best way to access data from another method in Vue?

Below is the code for my API call:

 async apiCall () {
    const [result1, result2] = 
    await Promise.all([
      get('lots/inputsOutputs', { locationId: '56464589a6d3b', fromDate: moment(this.dateRange[0]).format('YYYY-MM-DD'), toDate: moment(this.dateRange[1]).format('YYYY-MM-DD') }),
      get('lots/inputsOutputs', { locationId: '5464564563ebd', fromDate: moment(this.dateRange[0]).format('YYYY-MM-DD'), toDate: moment(this.dateRange[1]).format('YYYY-MM-DD') })
    ]);
    this.Loading = false;
    return [result1, result2];
  }

Answer №1

To begin with, it is entirely possible to invoke the function within another function of your choosing to retrieve the variables first and employ the await keyword to pause execution until the promise is resolved.

async apiCall () {
    const [result1, result2] = 
    await Promise.all([
      get('lots/inputsOutputs', { locationId: '56464589a6d3b', fromDate: moment(this.dateRange[0]).format('YYYY-MM-DD'), toDate: moment(this.dateRange[1]).format('YYYY-MM-DD') }),
      get('lots/inputsOutputs', { locationId: '5464564563ebd', fromDate: moment(this.dateRange[0]).format('YYYY-MM-DD'), toDate: moment(this.dateRange[1]).format('YYYY-MM-DD') })
    ]);
    this.Loading = false;
    return [result1, result2];
  },
  async myFunction() {
    const [result1, result2] = await apiCall(); 
    // add your code here
  }

If the function resides in the same component, you can utilize the data property to hold the results. Alternatively, you have the option to utilize Vuex, LocalStorage, or an EventBus to store them, although this may be excessive.

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

Generate a revised object from a function and return it to the caller

What is the most efficient way to update and return a new object from a function? I came up with this function: export const addItemToCart = (currentCart, item) => { const { name, ...otherProps } = item; // if the item is already in the cart if ...

Error in TypeScript code for combined Slider and Input onChange functionality within a Material-UI component

HandleChange function is used to update the useState for Material-UI <Slider /> and <Input />. Here is the solution: const handleChange = (event: Event, newValue: number | number[]) => { const inputValue = (event.target as HTMLInputEle ...

Is it possible for :hover to function with td elements in jQuery?

I created an HTML Table that includes a hidden infobox within one of the td elements. <style type="text/css"> .infobox{ display: none; background-color: #FFDB8F; font-size: 11px; } td { border: 1px solid; ...

Using jQuery to toggle between open and closed states upon clicking

I've been working on a script that allows me to expand an element when clicked, change its content, and then minimize it again with another click Here's the jQuery code I came up with: $(".servicereadmore").click(function () { $('.myin ...

Directive Template with Dynamic Fields (AngularJS)

I am interested in creating a custom directive that can bind to any object, allowing me to specify the field used in the template for display. Previously, I was limited to using {{item.Name}}, but now I want the flexibility to define the display field. Cu ...

Looking for assistance with getting 2 functions to run onLoad using Ajax - currently only 1 is operational

In the coding journey, I first implemented shuffle functions for arrays which was successful. Then, I proceeded to define two global variables that would dictate the random order in which images are displayed on the webpage. The variable picOrder was meant ...

Can the URL be updated in Vue Router without navigating to a new page?

I am working on a Nuxt.js website and trying to implement a "Load more" button on the /catalog page. When clicking on the button, I want to load more products without navigating to a new URL like /catalog/page_2 (?page=2 is not an option). If I use $router ...

tips on displaying a div dynamically in a specific location

Currently, I have implemented HTML textBoxes on my website. However, I am looking to validate these textBoxes using JavaScript. Rather than displaying a traditional alert popup for invalid data input, I would like to show a div next to the specific textBox ...

Retrieving selective attributes from Cosmos DB NoSQL using NodeJS/Javascript: Exploring the readAll() method for retrieving specific attributes instead of the entire object

Imagine having the following set of documents in your Cosmos DB (NoSQL) container: [ { "id": "isaacnewton", "fullname": "Isaac Newton", "dob": "04011643", "country": &q ...

Scrolling to does not function properly with Material UI tabs

Looking for a solution to scroll to a specific div when clicking on a tab in Material UI Tabs using UseRef and ScrollTo. Check out the sandbox link here: https://codesandbox.io/s/exciting-sound-mrw2v Currently, when I click on Tab 2, I expect it to autom ...

Adjust Mui Autocomplete value selection in real-time

I have implemented Mui AutoComplete as a select option in my Formik Form. <Autocomplete disablePortal options={vendors} getOptionLabel={(option) => option.vendor_company} onChange={(e, value) => {setFieldValue("vendor_id", value. ...

Back from the depths of the .filter method encased within the .forEach

I have been working on this code and trying to figure it out through trial and error: let _fk = this.selectedIaReportDiscussedTopic$ .map((discussionTopic) => {return discussionTopic.fk_surveyanswer}) .forEach((fk) => { ...

Tips for customizing MUI PaperProps using styled components

I am trying to customize the width of the menu using styled components in MUI. Initially, I attempted the following: const StyledMenu = styled(Menu)` && { width: 100%; } `; However, this did not have any effect. After further research, I ...

What role does a promise play in rendering code asynchronous?

While we often use promises to avoid the dreaded function callback hell, a question remains: where exactly in the event loop does the promise code execute and is it truly asynchronous? Does the mere fact that the code is within a promise make it asynchron ...

Puzzled by the unexpected error I encountered while using Node.js (require.js)

My script was running smoothly until I encountered a sudden error: undefined:3 <!DOCTYPE html> ^ SyntaxError: Unexpected token < at Object.parse (native) at Request._callback (C:\Users\Tom\Pictures&bso ...

Is there a way to escape from an iFrame but only for specific domains?

if (top.location != self.location) { top.location = self.location.href; } If my website is being displayed in an iFrame, this code will break out of it. But I want this to happen only for specific domains. How can I perform that check? ...

What steps do I need to follow in order to properly execute this HTTP request?

Recently, I came across this amazing tool called SimplePush.io that is perfect for one of my projects. It works flawlessly via curl, as shown on their website: ~ $ curl 'https://api.simplepush.io/send/HuxgBB/Wow/So easy' or ~ $ curl --data &ap ...

Convert JavaScript object into distinct identifier

I have a data object where I'm storing various page settings, structured like this: var filters={ "brands":["brand1","brand2","brand3"], "family":"reds", "palettes":["palette1","palette2","palette3"], "color":"a1b2" }; This object is ...

Invoking a Vuex action inside another Vuex action

After transitioning to the Vuex store, I've been steadily moving forward. However, my current hurdle involves invoking an action from within another action in Vuex. My grasp on Vue.js is still a work in progress. Current versions Vue 3 Vuex 4 If nec ...

Can a v-model be utilized within a component's template?

Is it possible to use the v-model syntax within a Vue component template? When the following code is included directly in an .html file, it functions correctly: <input type="text" v-model="selected_service_shortname"> However, placing the same cod ...