The response from a GET request contains data, however, attempting to access the .data property specifically returns undefined

Sorry if my terminology isn't quite right, I'm still new to fullstack development.

Hello there! Currently, I am attempting to retrieve all users from my database. Upon executing the get() request, the client is receiving an OK response as shown in the image below:

https://i.sstatic.net/DPVqk.png

The issue arises when I attempt to access the .data, it returns undefined.

Below is a snippet of my Vue Component:

import UserService from '@/services/UsersService.js'

export default {
  data () {
    return {
      users: null
    }
  },
  async mounted () {
    // Performing a GET request to fetch all users.
    this.users = UserService.index().data
    console.log('The response is OK', await UserService.index())
    console.log('attempting to access .data results in ', await this.users)
  }
}

Function index() definition:

import Api from '@/services/Api'

export default {
  index () {
    return Api().get('users')
  }
}

Everything seems to be functioning correctly, except for the fact that I am getting back undefined data...

Answer №1

Did you overlook the importance of fetching the data asynchronously?

  async mounted () {
    // GET request for all users.

-   this.users = UserService.index().data
+   const res = await UserService.index()
+   this.users = res.data

    console.log('The response is OK', await UserService.index())
    console.log('when trying to fetch the .data I am getting  ', await this.users)
}

Your correct utilization of await in the first console.log could be the reason behind the successful data return.

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

Identifying Changes in ReactJS Pages

As I delve into learning ReactJS, I have been experimenting with various websites that utilize this technology. Presently, my focus is on making an AJAX call to an API based on the URL of a page. The issue arises when clicking a link breaks my code due t ...

Provide JSON data from the index method to the index.html file located in the public directory

I'm currently working on building a single page application using Rails as the backend, since it's the only framework I am familiar with. All my project files are stored in the public folder, and I've also set up npm and jspm to incorporate ...

Send the NameSpace to the object and store it in the local storage

Hey there! I've developed an Android application that accesses the device certificates to retrieve specific information (APPCID). handleCertificate(appId) { OData.defaultHttpClient = sap.AuthProxy.generateODataHttpClient(); this.factory.connectionDa ...

Is it possible to alter the input value dynamically before submitting the form or refreshing the

I am looking to automatically update a hidden input value to either "0" or "1" based on whether a user fills out the phone number field. My current code is below: <script> if(document.getElementById('user-tel').value!='') { docu ...

altering a PHP variable via a JavaScript variable in a query string

My current task involves validating textbox input against a specific set of words in a predefined order from the database to check for matches. Upon successful validation, the user's "quest" level increments, triggering a new set of words to be fetche ...

Personalizing MaterialUI's autocomplete functionality

Trying to implement the material-UI Autocomplete component in my react app and looking for a way to display a div when hovering over an option from the list, similar to what is shown in this reference image. View example If anyone has any tips or suggest ...

What is the best way to retrieve JSON data in ReactJS through ExpressJS?

Exploring the realms of reactjs and expressjs, I am seeking guidance on how to extract data from reactjs and store it in a variable. My current achievement includes successfully executing res.send to display the data. app.get('*', (req, res) =& ...

Determining when a function is triggered from the JavaScript console

Is there a way to conceal a function in JavaScript console so that it's inaccessible for calling? Let me give you some context - let's say I have a JavaScript function that adds records to a database using Ajax. The issue is, anyone can call thi ...

"Why is the action.js section showing as undefined?

I'm facing an issue with the action.js file where I keep getting undefined as a response from the service. However, when I debug the service.js API function, it shows the correct response. Here is the code snippet for better understanding: Action.js ...

The integration of Meteor.js with an external Mongo database is causing issues with logging in to Mongo

In my project, I am using a meteor.js application along with mongo db (2.6). To create a user in mongo, I followed these steps: use meteor db.createUser( { user: "meteor", pwd: "password", roles: [ { role: "userAdmin", ...

Tips for dynamically changing the color of a React Native style based on data conditions

Just starting with react native. I'm working on a basic quiz feature for my app. I've created an api that provides questions, answers, and a boolean value indicating the correct answer, Something like this : { "question:"Demo quest ...

When an SVG image is embedded, its color may not change even after being converted to an inline SVG

I've inserted an SVG using an img tag. When hovering over it, I want the fill color of the SVG to change. I attempted to convert the SVG to inline SVG following this method, but it doesn't seem to be working as expected. No console errors are b ...

What is the best way to leverage multiple random YouTube v3 API keys simultaneously?

I have the following code snippet and I am looking to randomly select an API key from a list of keys: function search() { // Clear Results $('#results').html(''); $('#buttons').html(''); // Get Form Input ...

What are the risks associated with allowing user-generated HTML or Javascript code on a website?

Is it really dangerous to allow users to edit HTML with Jinja2 templates and access some server-side variables that will be rendered later? I know Google uses Caja Compiler to sanitize and sandbox HTML served from Google Apps Script. Should I be concerned ...

Is there an Angular directive that can replicate a mouseenter event?

Is there a way to simulate a mouseenter event with a directive? I have been searching for a directive that can simulate a mouseenter event, but all I have found so far is one that binds a function to mouse over or karma tests for simulating mouse over. W ...

Vue - component props not properly updating when object changes are made

Within the main structure, I have both obj and newObj objects. I am monitoring any changes that occur within the obj object using deep: true, and then updating newObj accordingly. Although in my vue debugger, it appears that newObj has been updated as exp ...

The ultimate guide to personalizing group titles in Angular UI-Select

Is there a way in Angular ui-select to customize the group label? I want to make it larger than the selection items as shown in the image below. https://i.stack.imgur.com/ofcak.png The list is currently grouped by country, but how can I adjust the size o ...

When an element is transferred to a different <div>, it does not automatically inherit its new CSS styles

There's an element with existing behavior that needs to be moved to meet new requirements without losing its original styles. The challenge is applying new styles to the element after it's been moved. For example: <div id="existingStructure" ...

Creating rows within a table in React.js using the map method: Techniques to follow

Here is my code snippet: const [tasks, setTasks] = useState(''); I am simulating data with a mock server. function fetchTasks() { axios.get('http://localhost:4000/tasks') .then(function (response) { ...

Is there a way to convert my function into a variable in order to execute an array of statements

I'm struggling to convert this code into a variable. I need to bind it inside a statement execute array. This is the code I am working on, which retrieves the current date and timezone. I attempted using $date = function() {}, echo $date(); but that ...