Executing axios within a JavaScript function without relying on global variables

I am currently exploring the usage of axios (https://cdnjs.cloudflare.com/ajax/libs/axios/0.17.0/axios.js) in a function to communicate with my backend and retrieve data.

The snippet of code provided is functional.

Instead of relying on a global variable to store the response, I am seeking an alternative method.

However, when attempting to move the variable myresponse into the function itself, I encounter difficulties capturing the output.

Is there a way to achieve this without resorting to using a global variable?

var myresponse = "xxx"

function getTimeData() {

    axios.get('/time')
    .then(function (response) {

    console.log(response.data);
        myresponse = response.data;
    })
    .catch(function (error) {
        myresponse = "error";
    });

    return myresponse;

}

console.log(getTimeData())

In this scenario, a local server running at "/time" returns a timestring.

Answer №1

Axios allows the use of global variables within its functions, but it's important to note that any values you want to access outside of axios should be set after receiving a response. For example:

var myresponse = "xxx"

function getTimeData() {

    axios.get('/time')
    .then(function (response) {
        myresponse = response.data;
        return myresponse;
    })
    .catch(function (error) {
        myresponse = "error";
        return myresponse;
    });
}

console.log(getTimeData())

Keep in mind that logging 'myresponse' before receiving a response may not display the correct value, as it will only be set once a response is received.


Here's a snippet of Vue code that shows how axios sends requests and receives responses asynchronously:

var HTTP = axios.create({
            baseURL: URL,
        })
methods:{
                getUsers(){
                    return HTTP.get('/users/admin')
                },
                deleteUsers(user){
                    HTTP.post('/users/admin',{
                        id : user._id
                    })
                    .then(()=>{
                        this.getUsers()
                    })
                }                   
            },
            created(){
               this.getUsers().then(res=>{
                   this.users = res.data;
               })
            }

Answer №2

If you are aiming to log the value at the end, there's no need for a separate variable. Simply include it in your function using async/await:

const fetchTimeData = async () => {
    try {
        const response = await axios.get( "/timer" );
        console.log( response.data );
    } catch ( error ) {
        console.log( error );
    }
};

fetchTimeData();

If you intend to utilize the retrieved value elsewhere, you can directly incorporate it within your function:

const fetchTimeData = async () => {
    try {
        const response = await axios.get( "/timer" );
        return manipulateData( response.data );
    } catch ( error ) {
        return handleErrors( error );
    }
};

fetchTimeData();

Answer №3

If you find yourself in need of gathering data from the axios library, a simple solution is to encapsulate the return statement.

var result;
function fetchData() {
    return axios.get('/data')
}

fetchData()
.then(function(response) { 
  result = response.data;
  console.log(result);
})
.catch(function(error) {
  console.error(error)
});

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

When you drag down on mobile Safari on an iPad, touch events may cease to fire in HTML5

When I implement event listeners to handle touch events like touchmove and touchstart document.addEventListener("touchstart", function(event){ event.preventDefault(); document.getElementById("fpsCounter").innerHTML = "Touch ...

How can I acquire a duplicate of a Webgl texture?

I have a webgl texture and I have stored it in a JavaScript variable var texture1 = CreateTexture() function CreateTexture(){ var texture = gl.createTexture() // more WebGL texture creation code here return texture } I am looking to create a copy o ...

What is the default parameter type in react-native?

Currently, I am delving into React-native framework. While browsing through the Facebook ListView sample page, I stumbled upon the below code snippet. _renderRow: function(rowData: string, sectionID: number, rowID: number) { .... Interestingly, I have n ...

Getting a 406 (Not acceptable) error when trying to perform an AJAX action in Rails 4

I am attempting to automatically refresh a specific partial view every 60 seconds on the homepage. To make it easier to manage, I have divided the actions into two routes. However, I am encountering an issue with the respond_to block and could use some ass ...

Transforming an AJAX call into a reusable function

My goal is to simplify my ajax calls by creating a function that can be reused. Although I'm unsure if I'm doing it correctly, I would like to attempt this approach. <script> $(document).ready(function(){ var reg_no=$("#reg_no").va ...

Presenting a trio of distinct tables each accompanied by its own unique button option

I am attempting to create a functionality where there are 3 buttons and when a user clicks on one of them, it shows the corresponding table while hiding the other two. I have experimented with using getElementById to manipulate the display property of the ...

Save essential data in local/session storage to have access to it even after the page is reloaded

Dear Team, we recently developed a single-page application that stores data in the root scope for access on other pages. While everything functions well in the regular flow, we encountered an issue with browser refresh. If a user refreshes the applicatio ...

AngularJS toaster doesn't seem to be appearing

I have integrated the angularjs toaster library into my project. Here are the necessary references: https://github.com/jirikavi/AngularJS-Toaster Added the following references for the library: <link rel="stylesheet" href="bower_components/Angu ...

Tips for capturing an express proxy error in React?

I set up an express server as a proxy for my React app, but I am facing an issue where I cannot get the error response back in my React code. No matter if I use `return next(err)` or `res.send(err)`, the latter gets stuck in the `then` block and does not t ...

Using .substr method interferes with the functionality of the alert method

I've been struggling to extract the hours and minutes from a Microsoft JSON string. Despite reading through numerous articles, including How do I format a Microsoft JSON date?, I have not been successful. Even when attempting to implement the example ...

several ngGrids and ngGridEventScroll

There are 2 separate ng grids on a single page, each with infinite scrolling that loads server-side data on ngGridEventScroll. scope.$on('ngGridEventScroll', function(event) { ... }); Each grid is designed to make its own unique server-side cal ...

Tips for creating multiple files using nodejs and express

I am currently working on developing a personalized code editor that consists of 3 textareas: html, css, and javascript. The objective is to save the data from each textarea into individual files. With the help of express and nodejs, I have successfully m ...

What is the proper way to retrieve a constant variable within a return statement?

Here is the code I have written: const keyToDisplayMessage = 'REGULAR_HOME'; const cf = format( { accountName: this.accountName, }, this.pageData.sucessMessages.keyToDisplayMessage, this.$route.name ); return cf; The ...

Locate the submenu item in relation to the main menu item within an external container

I'm working on modifying the behavior of a site's sub-menu. The current sub-menu is displayed as a drop-down, but I want it to show up in a separate horizontal div instead. Here's what I have accomplished so far: jQuery(document).ready(fun ...

How can HTML5 geolocation be utilized to provide real-time latitude and longitude coordinates for integration with the Google Maps API?

I am currently working on a project where I need to dynamically fetch longitude and latitude values from the browser geolocation and then include them in the options array for the Google Maps API. Here is the code snippet I am using: function initMap(){ ...

Completes a form on a separate website which then populates information onto a different website

Creating a website that allows users to login and view various complaint forms from government websites or other sources. When a user clicks on a link to file a complaint, they will be redirected to the respective page. However, I am looking for a way to ...

Error message "Uncaught TypeError: Cannot read property 'domElement' of undefined" occurred in webgl-template.html at line 69 in Three.js

I found this interesting code on <!DOCTYPE html> <!-- saved from url=(0056)https://www.benzedrine.ch/vistaprint/webgl-template.html --> <html> <head> <meta http-equiv="Content-Type" content="text/html; charse ...

Watch the Newest Vimeo Showcase Reel

I have a new project where my client is requesting to display the latest video from a specific Vimeo Portfolio. I already have a script that can fetch the latest video from the entire account using JavaScript as shown below: http://codepen.io/buschschwick ...

Retrieve information from a JSON file by utilizing the JSON file itself as a variable

Currently, I am attempting to extract the URL of an attached photo using JSON. I am utilizing the value of the data from the JSON key "HousePhoto1" to then access the value from the post_media data. The issue I am encountering is that my JavaScript code fa ...

Error encountered: Javascript throws an error while trying to initialize the Bootstrap datetimepicker if the input value only

My requirement is to utilize the DateTime Picker plugin and load only the Time picker component. To achieve this functionality, I have initialized my input field in the following manner, allowing only time selection: jsfiddle: <div class="input-group ...