Access the outcome external to the Vue instance

Currently, I am utilizing VUE and Axios to retrieve a JSON from an API. However, I encountered an issue when attempting to assign the received results from the API into a variable outside the Vue Instance as it is showing that the item is null. (When I check in the console by calling vueinstance.results, I do get the results).

var vueinstance = new Vue({
    el: '#app',
    data(){
        return {results: null }
         } ,
    methods: {
        callApiSearch: function (searchQuery) {
            axios
                .post('api/search', searchQuery)
                .then(response => (this.results = response.data))
        }
    }
});

var ajaxSearch = function callApi(searchQuery) {
    //Construct Search Query
    if (typeof searchQuery === "string" || searchQuery instanceof String) {
        searchQuery = { Query: searchQuery };
    }
    vueinstance.callApiSearch(searchQuery);

    var test = vueinstance.results; <====== **THE VALUE HERE IS RETURNING AS NULL**

}

If anyone has any insights on how to resolve this issue, your assistance would be greatly appreciated. Thank you.

Answer №1

The method callApiSearch is carrying out an asynchronous operation; the callback then will be triggered after the HTTP response has been received, which happens after you have accessed vueinstance.results.

I recommend familiarizing yourself with JavaScript async concepts, promises, concurrency, and related topics to gain a better understanding of this issue. You can find plenty of online resources on these subjects.

To resolve this, ensure that your callApiSearch function returns the promise:

callApiSearch: function (searchQuery) {
  return axios
    .post('api/search', searchQuery)
    .then(response => (this.results = response.data))
}

When calling the method, use then on the returned promise to execute code once the request is complete:

vueinstance
  .callApiSearch(searchQuery)
  .then(() => {
    console.log(vueinstance.results)
  })

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

Delete the event handler if the original selector used to set up the handler is unknown

I need to remove an event handler from the element. The current handler is added by a third-party plugin, and I want to prevent its behavior. As far as I know, the functions off() and unbind() require the original selector to be used. The issue arises b ...

When the parent div contains at least four divs, show the scroll arrow containers

In my code, there is a parent div that holds multiple child divs. If the number of child divs within the parent div exceeds 4, I want to show the scroll arrow containers. If it's less than 4, then those arrow containers should not be displayed. The ...

Creating an engaging user experience with a Django form

Creating a dynamic calculator <div id="calculator"> <h2>Calculate the price of sawing materials</h2> <form method="post" action="{% url 'products' %}"> {% csrf_token %} & ...

Troubleshooting problem with updating a record in the MongoDB using Node.js and

Currently, I am developing a REST API using Node, Express, and MongoDB. I have successfully implemented fetch, create, and delete functions but facing issues with the update function. Every time I attempt to test it using Postman, the code hangs, the serve ...

Using JQuery and Bootstrap: Adding an image from a selection of images to a carousel

As a beginner in the world of JQuery, I am currently working on creating a customizable carousel where users can select pictures to add to the carousel with just one click. On the left side of the page, there is a selection of images to choose from, while ...

Utilize a Random Color Generator to Match Background Color with Border Color in Full Calendar

I'm currently developing a full calendar to showcase a clear and aesthetically pleasing schedule for my client. I am attempting to assign a unique color to each event by generating random colors on every page load using codes. However, I have encounte ...

Navigating focus to an overlay using Selenium

I am facing an issue with an overlay displaying terms on top of the main window. The scrollbars are not behaving as expected: https://i.sstatic.net/nzaUa.png The new window does not register as a separate 'window' or tab, so traditional methods ...

Trigger an analytics event from a background chrome extension

I've encountered a challenge with sending an event to Google Analytics from background.js, which is the background script of my Chrome extension. This is the code snippet I added to my background.js file: var _gaq = _gaq || []; _gaq.push(['_set ...

Differentiating Typescript will discard attributes that do not adhere to an Interface

Currently, I am working with an API controller that requires a body parameter as shown below: insertUser(@Body() user: IUser) {} The problem I'm facing is that I can submit an object that includes additional properties not specified in the IUser int ...

Submitting FormData through the GET method with XMLHttpRequest

When the method of the senderform is set to POST, everything functions correctly. However, changing the method to GET results in not receiving any data on the server. function ajaxSubmit(destinationElement, senderform) { var xmlreq = new XMLHttpReque ...

Error: The function in Knockout js is not defined as undefined

I am attempting to insert specific data into an array, as shown below: Below is my code: Create.html Field Name: Display Name: ...

Vue.js is limited in its ability to efficiently partition code into easily loadable modules

My current issue: I am facing a challenge with splitting my vue.js code into chunks. Despite trying multiple examples from tutorials, I am unable to successfully separate the components and load them only when necessary. Whenever I attempt to divide the c ...

Is it beneficial to store commonly used data in JSON format within a MySQL database?

When working with prospects in a Vue.js app, the main focus is on managing various elements like contacts, listings, and other objects/tables. Each prospect can have multiple interactions, with some having up to 30 or more per prospect, while others like e ...

Combining Key-Value pairs in JavaScript using JSON

I am currently working on parsing a JSON object to extract the key and value combined into a variable. The desired output I want from the provided JSON is: "/" - 7.84 GiB; "/opt" - 4.86 GiB; "/usr" - 4.80 GiB While I can retrieve objects using my code sn ...

Clicking on any of the identical components should trigger just one post request, updating the state accordingly

I'm facing a small issue and could use some guidance on how to resolve it. I've created a simple Starrating component with five stars that change state when clicked. The problem arises because the Starrating component is nested within another com ...

Encountering a TypeError when the 'on' event is triggered by 'byId' in Do

Currently, I am facing an issue with a module that includes a switch statement generating content and various on events waiting based on the content inserted into the DOM and the trigger activated. The problem arises when using on event handlers with dom. ...

Server-side-rendering is encountering an issue with a package that is restricted to running solely in a browser

I have integrated localForage into my SSR Nuxt project. and within my Nuxt-Page-Component ... <script> import localforage from 'localforage'; export default{ mounted(){ localforage.getItem('something', value => { ...

Display the last 3 characters of an input field when it is in focus

I want the minutes in my input to only show up when the input is focused. Can this be achieved? Currently, I am using jQuery to display the full time, but I prefer to always have the full time as the value and only show what is necessary. Another issue i ...

Suggestions for retaining buttons functionality during drag and drop operations using jQuery UI?

My goal is to create new preset buttons when a button is dropped into the "timeslot" div. However, I am struggling to achieve this and ended up creating a function called "init()" which removes all existing buttons and generates new preset buttons every ti ...

Triggering events in vue-router

I have two components called MyItem.vue and ChangeItem.vue. I'm attempting to emit an event in the ChangeItem.vue component and catch it in the MyItem.vue component, but for some reason, it's not working as expected. MyItem.vue <template> ...