Ways to display a variable prior to making an axios request

I have a get request that saves the result in a variable named name_student. How can I access this variable in other methods? Or how should I declare it?

Here is the code snippet:

getStudent(){
  axios.get('https://backunizoom.herokuapp.com/student/2')
        .then((result) => {
          console.log(result.data)
        this.name_student=result.data.name
        console.log(name_student)
        
    })
    console.log(name_student)
},

Answer №1

Using Shared Data Properties

In response to suggestions from @scar-2018 in the comments section, it is recommended to define name_student as a data prop so that it can be accessed by all component methods and hooks:

export default {
  data() {
    return {
      name_student: '',
    }
  },
  methods: {
    getStudent() {
      axios.get(/*...*).then((result) => {
        this.name_student = result.data.name

        this.updateStudentName()
      })
    },
    updateStudentName() {
      this.name_student += ' (student)'
    }
  }
}

Handling Asynchronous Data Access

If you are encountering issues with accessing data asynchronously and seeing undefined when logging name_student, it may be due to the asynchronous nature of the axios callback. Ensure that you are logging this.name_student after it has been modified by axios:

axios.get(/*...*/).then((result) => {
  this.name_student = result.data.name
  console.log(this.name_student) // => 'foo' ✅
})

console.log(this.name_student) // => undefined ❌ (not yet set)

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

The jqGrid displaying data with datatype set to "jsonstring" is only showing the first page

When my JqGrid receives data from the server in JSON format, I use the following parameters: _self.GridParams = { rows: 7, page: 1, sidx: '', sord: '' } Once the data is retrieved, it is stored in the variable 'data': Objec ...

Issue with Bootstrap 5 Modal Overlay

I created a function that automatically generates a modal to save time and keep the code organized. This way, the HTML and JS related to the content of the modal are all in one PHP file, rather than mixed in with the file calling the modal: function new_mo ...

Why does the Angular page not load on the first visit, but loads successfully on subsequent visits and opens without any issues?

I am currently in the process of converting a template to Angular that utilizes HTML, CSS, Bootstrap, JavaScript, and other similar technologies. Within the template, there is a loader function with a GIF animation embedded within it. Interestingly, upon ...

Puppeteer: Eliminate hyperlinks on webpage

I am currently using Node.js and Puppeteer to convert a webpage into a .pdf-file. Everything functions as expected, however, I need assistance in removing all the links on the page before converting it to a .pdf. This is necessary because the resulting .p ...

Which approach is more impactful: consistently sending an ajax request or breaking down the result within a function?

My JSON data consists of news entries with titles, text, and dates. Here is an example: { "news": [ {"title": "some title #1","text": "text","date": "27.12.15 23:45"}, {"title": "some title #2","text": "text","date": "26.12.15 22:35"}, ... ...

Save room for text that shows up on its own

I am currently dealing with a situation where text appears conditionally and when it does, it causes the rest of the page to be pushed down. Does anyone know the best way to reserve the space for this text even when it's not visible so that I can pre ...

The checkbox is failing to display as checked even after its value has been dynamically set to true

Currently, I am immersed in a project within ASP.NET MVC that involves displaying data on a page where users can interact by selecting checkboxes to make changes. In cases where there are numerous checkboxes present, a "Select all Checkboxes" button become ...

trouble with maintaining nodejs mariadb connection

Hello, I am working with nodejs to create a rest API However, I have encountered an issue Let's take a look at the code var http = require('http'); var url = require('url'); var mariadb = require('mariadb'); http.c ...

What is the best method for setting up message scheduling for a Microsoft Teams bot based on different time

I am trying to figure out how to send messages to users from my bot at specific time intervals. Currently, I'm using agenda for scheduling messages, but I've run into an issue with the timezone discrepancy - agenda is 5:30 hours behind my timezon ...

Trigger the React useEffect only when the inputed string matches the previous one

Currently, I am in the process of creating my own custom useFetch hook. export const useFetch = <T extends unknown>( url: string, options?: RequestInit ) => { const [loading, setLoading] = useState(false); const [error, setError] = ...

Struggling to successfully submit data from an API to the project's endpoint, encountering Error 405 method rejection

I'm working on integrating data from the openweathermap API into my project's endpoint to update the User interface. Everything seems to be functioning correctly, except for when I attempt to post the data to the endpoint. What am I overlooking h ...

Using JavaScript to locate a child element within its parent

What is the most effective approach to locate a child element (using class or ID) of a specific parent element using only pure JavaScript without relying on jQuery or other frameworks? In this scenario, I am interested in finding child1 or child2 within p ...

How to access selection range styles using JavaScript

It is common knowledge that we can retrieve the selection of text in JavaScript using the following method: var range = window.getSelection (); However, how can we obtain the style of this selection? For example, when I select bolded text or italicized ...

Finding it difficult to grasp the concept of enabling CORS through an ajax request

I'm struggling to figure out how to enable CORS while using Ajax to send data to a remote server on a different domain. Despite researching extensively and reading numerous Stackoverflow threads, I can't seem to make sense of it all. I understand ...

unique navbar color transition effect specifically for the homepage

I have successfully created a function called changeColour in my code that changes the color of the navbar when scrolling past a certain point. However, I am encountering an issue where I only want this effect to be applied on the Home page. I would like a ...

generate an object with the forEach method

When I receive data from a graphql query, my goal is to structure an object like the example below: const MY_DATA = [ { id: 'bd7acbea-c1b1-46c2-aed5-3ad53abb28ba', imageUrl: defaultUrl, name: 'Johann', } ...

Autocomplete with Avatar feature in Material UI TextField

Is it possible to display an avatar in the text field of the autocomplete material-ui component when using the getOptionLabel prop, which only accepts a string? The expected UI shows a profile picture and name for each option. Can we achieve the same thi ...

req.next does not exist as a function [END]

I am currently working on developing a website and I have encountered an issue in the dashboard stage. The error message TypeError: req.next is not a function keeps appearing, particularly when trying to create a subpage for the dashboard. I am utilizing t ...

cracking reCAPTCHA without needing to click a button or submit a form (utilizing callback functions)

Currently, I am facing a challenge with solving a reCaptcha on a specific website that I am trying to extract data from. Typically, the process involves locating the captcha inside a form, sending the captcha data to a captcha-solving API (I'm using ...

JSON does not send information to the specified web address

Attempting to send some data to the following URL: " $(function() { var frm = $(document.myform); var data = "?lm_po_id=154668&authentication=ThisisAuth&description=ThisIsDesc";//JSON.stringify(frm.serializeArray()); ...