Using Vue Js, I utilized Axios to make a call within a function, receiving and storing the retrieved data into an array

While working inside the function shown in the screenshot, I am encountering an issue when trying to access the data retrieved from the backend using axios.get. After exiting the axios block, the values of the array appear as undefined when I attempt to print them.

The data I am fetching from the backend is in string format. My aim is to utilize this data across different methods by returning it. Unfortunately, I have not been able to find a solution to this problem.

getReasonsForWaitingCustomer() {
  this.adimKodlariLastString = "";
  if (this.$route.params.status == "musteri-bekleniyor") {
            axios.get(URL + "xxx/xxx?xxx=xxx)
                .then(response => {
                    for (var i = 0; i < response.data.data.length; i++) {
                        if (this.stepCode.includes(response.data.data[i].adim_kodu) == false) {
                            this.stepCode.push(response.data.data[i].adim_kodu);
                        }
                    }
                    for (var j = 0; j < this.stepCode.length; j++) {
                            this.adimKodlari += this.stepCode[j] + ",";
                        }
                    this.adimKodlariLastString = this.adimKodlari.slice(0, -1);
                    console.log("inAxiosThen",this.adimKodlariLastString);
                })
        }
        console.log("afterAxios",this.adimKodlariLastString);
return "apfapofapkapfka" --> It's working
return this.adimKodlariLastString --> It's not working. I want this to work.
},

Most solutions I've come across involve utilizing the incoming value within HTML tags. However, my requirement is to make use of this value within methods.

I am able to retrieve the desired string values when they are within the .then(response) block and checked through the console.

However, outside the .then() block, I face difficulties in accessing these values through the console.

Answer №1

If you want to retrieve data using axios calls, keep in mind that they are asynchronous. An easier and more organized approach would be:

const response = await axios.get('url')
console.log(response.data)
this.adimKodlariLastString = response.data
// proceed with your logic here

Alternatively, if you prefer to work with your existing code, you can simply add:

await

prior to axios (although using pure Promises may lead to nested Promises).

Answer №2

Currently, this function represents the final status of my work. It is operational and producing successful results.

async getReasonsForWaitingCustomer() {
  let lastAdimCodes = "";
  let stepCodeArray = [];
  let adimKodlari = "";
  if (this.$route.params.status == "xxx") {
            const response = await axios.get(URL + "xxx/xxx");
                    for (var i = 0; i < response.data.data.length; i++) {
                        if (!stepCodeArray.includes(response.data.data[i].adim_kodu)) {
                            stepCodeArray.push(response.data.data[i].adim_kodu);
                        }
                    }
                    for (var j = 0; j < stepCodeArray.length; j++) {
                            adimKodlari += stepCodeArray[j] + ",";
                        }
                    lastAdimCodes = adimKodlari.slice(0, -1);
        }
        console.log("adimKodu",lastAdimCodes);
      return lastAdimCodes;
},

Screenshot of Promise in console

I reviewed their solutions, but I found them confusing. They manually set a value and then called it as the result. I am unsure how to extract my incoming data in PromiseResult.

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

Typescript encountering onClick function error during the build process

My current challenge involves creating a submit function for a button in my application. However, when I attempt to build the project, I encounter a typing error that is perplexing me. Despite trying various methods, I am unable to decipher how to resolve ...

What could be causing React to throw an invalid hook error when using useRoutes?

I encountered an error while attempting to add a new route to my project. import React from "react"; import News from "./NewsComponents/News"; import Photos from "./PhotosComponents/Photos"; import Contact from "./Contact"; import Home from "./Home"; ...

Using Node.js for HTML redirections involves creating routes and setting

I am currently attempting to connect my Node.js API with my HTML pages. For the most part, everything is functioning correctly, but I have encountered some confusion along the way. Is there a more efficient method for redirecting an HTML page? Typically, ...

Encountering an undefined error while attempting to retrieve an object from an array by index in Angular

Once the page is loaded, it retrieves data on countries from my rest api. When a user selects a country, it then loads the corresponding cities for that country. Everything is functioning properly up to this point, however, upon opening the page, the city ...

Guide on managing firebase and webrtc tasks within a client-side component using Next.js 13

I developed a Next.js 13 application to share the camera feed using WebRTC and Firestore. Below is my page.tsx file where I am facing some challenges. I can't make this server-side because I'm using React hooks, and moving it to the client side i ...

Utilizing Vue.js: accessing a global value within a template string

I am working on a simple Vue.js application with the following structure: index.html (only the <body> for brevity) <div id="root"></div> main.js var settings = { title: 'My App', } new Vue({ el: '#root', tem ...

Update the image within the svg tag

I am attempting to modify a preexisting SVG element within an HTML document. Here is the current code: <svg class="logo" viewBox="0 0 435 67"> <!-- IMAGE DIMENSIONS --> <use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#logo- ...

Is it possible to import data into a script?

When working with Angular, I am attempting to: $scope.data = "<script> alert('hi'); </script>"; Unfortunately, this approach does not seem to be effective. I also experimented with adding ng-bind-html but did not achieve any success ...

Oops! A JSON parsing error occurred due to the presence of an unexpected token '}'

I encountered an issue while trying to develop a registration route using passportjs. When sending a request via Postman, I received the following error message: SyntaxError: Unexpected token } in JSON at position 119    at JS ...

What is the best way to eliminate the "onclick" attribute from an HTML element using JavaScript?

Is there a way to make my code only execute the onlick function after a button is pressed? I want to prevent any action from happening before that. <!-- deactivate onclick function --> <div class="boardsection2" id="2_8_7" oncl ...

Access specific data from a jQuery event

How can I retrieve the value of a custom attribute called itemID in order to include it in the URL just like I do with id? Here is the JavaScript code: <script type="text/javascript"> $(document).ready(function(){ $('.eventImage').cl ...

Record every function within the array prototype

Exploring methods that can be accessed on an array object: > console.log(Array.prototype) [] undefined > console.log(Array.prototype.push) [Function: push] Is there a way to view or log all properties/methods accessible on an object's prototyp ...

Upon the second click, the addEventListener function is triggered

When using the window.addEventListener, I am encountering an issue where it only triggers on the second click. This is happening after I initially click on the li element to view the task information, and then click on the delete button which fires the eve ...

Retrieving the value of a <select> element using React.useState in a Nextjs environment

Encountering an issue in Nextjs involving the useState function from React. There is a select element with multiple options. Upon selection, the useState should store the value of the selected option. const [value, setValue] = useState('') ... ...

When updating the innerHTML attribute with a new value, what type of performance enhancements are implemented?

Looking to optimize updating the content of a DOM element called #mywriting, which contains a large HTML subtree with multiple paragraph elements. The goal is to update only small portions of the content regularly, while leaving the majority unchanged. Co ...

A step-by-step guide on changing the class of a focused contenteditable element with a button click using jQuery

I need assistance changing the class of an element within a contenteditable div. Here is my current code: <button>swap class</button> <div contenteditable="true"> <h1 class="line-height-1">Your Headline Here</h1> </di ...

The reactivity of arrays in Vue components' props is limited

I've got an array with component data that I'm attempting to render using v-for <div :style="style" class="editor-component" v-for="(component, index) in components"> <Component :is="component.name" v-bind="component.o ...

Deleting content in a text area when specific text is entered

Is there a way to clear the textarea value if I type in <br>? The code I have right now is shown below. I understand that this may seem like an odd request, but I am experimenting with a typing effect. function eraseText() { document.getElemen ...

a pair of browser windows displaying a web application built with ASP.NET MVC

We are currently in the process of developing an ASP.NET MVC web application for internal use within our organization. Our users' productivity can greatly benefit from having a larger screen space, which is why we have decided to provide each user wit ...

Managing OAuth2 redirections on the frontend: Best practices

I am currently working on implementing an OAuth2 flow for a Single Page Webapp, but I am facing challenges in dealing with Frontend/JavaScript redirects. Regarding the backend setup, I have it all sorted out: utilizing a library that takes care of everyth ...