How can I retrieve data from an API in Vue using promises?

Within my repository.js file, I have the following code snippet:

async getAllContactRequests() {
    return new Promise(() => {
      axios
        .get("http://127.0.0.1:8000/api/contactRequests", {
          headers: { "Authorization": "Bearer " + sessionStorage.getItem("user_token") }
        })
    })
  }

Meanwhile, in my Vue component, the setup is as follows:

<script>
import repository from "@/api/repository";

export default {
  name: "posts-index",

  data() {
    return {
      apiData: null,
    };
  },

  async mounted() {
    console.log("This message prints");
    this.apiData = await repository.getAllContactRequests().then(result => result.data);
    console.log("However, this one doesn't");
  },
};
</script>

Despite the structure being sound, for some reason, the data retrieval process from the promise isn't successful and any subsequent lines of code fail to execute. What could be causing this issue?

Answer №1

If the API response is in JSON format, you have the option to streamline the code snippet above like so:

async fetchAllContactRequests() {
    return axios
        .get("http://127.0.0.1:8000/api/contactRequests", {
          headers: { "Authorization": "Bearer " + sessionStorage.getItem("user_token") }
        })
  }

This simplifies things because Axios already returns a Promise, eliminating the need for wrapping it redundantly in another Promise.

To handle the response data, wait for the API call by using async/await:

import repository from "@/api/repository";

export default {
  name: "posts-index",

  data() {
    return {
      fetchedData: null,
    };
  },

  async mounted() {
    const result = await repository.fetchAllContactRequests()
    if (result && result.data) {
       this.fetchedData = result.data
    }
  },
};

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

Unlock the full potential of Angular Material Framework by leveraging Custom Palettes

I'm experiencing some issues implementing Custom Palettes with Angular Material Framework. I'm still trying to grasp the concept of using a custom theme. In the Angular configuration file. $mdThemingProvider.definePalette('crmPalette' ...

Are there any methods to alter the current preFilters within jQuery?

Is there a way to access and manipulate the internal jQuery preFilters using the jQuery.ajaxPrefilter() function? In version 1.11.1, I noticed a private preFilters object declared on line 8568, but it doesn't seem like there is a built-in method to in ...

Web Audio API functions are encountering a playback issue on iOS 13.3, despite working smoothly on previous iOS versions

I have been developing an audio visualizer using the web audio API. It was functioning smoothly on PC, however, after upgrading to iOS 13.3, it no longer operates on Apple mobile devices. The root cause of this issue remains a mystery to me. The problem s ...

Is there a way for me to include a prefix in the path where Vue pulls its component chunks from?

I recently incorporated VueRouter into my project and encountered an issue with the asset URL not being correct. Instead of displaying www.example.com/js/0.main.js The URL it generates is www.example.com/0.main.js Any suggestions on how to include the ...

establishing the dimensions of table data cells

I'm facing a challenge with setting the width and height for table data that changes dynamically based on different values. The dimensions of the table itself are not definite, so I need to find a solution. Here's the code snippet I'm curren ...

Is it possible to authenticate both users and admins within the same collection in Mongoose when using Node.js with Express? Can aggregation be used for this purpose?

this is my custom schema const mongoose = require ('mongoose'); const adminSchema = new mongoose.Schema({ name:String, password:String, user:[{ name:String, email:String, password:String } ] }) var ...

Refresh the Page or URL After Submitting a Form using JavaScript or PHP

Just a heads up: I'm fairly new to the world of web development. Currently, I'm in the process of crafting an event calendar using CodeIgniter. However, I've hit a bit of a snag. Whenever I try to update an event using JavaScript, the page ...

"Efficiently setting up individual select functions for each option in a UI select menu

I've integrated UI Selectmenu into my current project UI selectmenu includes a select option that allows for setting select behavior across all selectmenu options, as shown in the code snippet below: $('.anything'). selectmenu({ ...

JQuery causing array to not update properly

I am attempting to splice an array to remove an object from it. My approach involves using angular-formly for form display, and AngularJs with JQuery to manage the data. Utilizing JQuery $(document).on("click", ".delete-me", function () { var id = $( ...

Issue with express-validator returning undefined value on forms set to enctype='multipart/form-data'

Currently, I am developing a login authentication application using basic node.js+express. While extracting values (such as name, email, etc) from the registration page, I utilize express-validator for validation. However, I encounter an issue where all va ...

Obtaining a UTC datetime value in BSON format using Node.js or JavaScript

I'm encountering an issue while attempting to save an entry in a MongoDB time series collection. The problem arises when storing the timeField, resulting in an error thrown by mongo. MongoServerError: 'blockTime' must be present and contain ...

Troubles encountered with the search bar filter functionality, implementing JS/JQuery within a Laravel blade template

Currently, I have a blade template containing a search bar for filtering purposes. The issue I'm encountering is that the filtering functionality doesn't seem to work as expected after removing Angular from the page entirely. The page is set up ...

Is there a way to retrieve the ReturnType of functions based on a parameter list in Typescript?

I am struggling with defining a main function myMainFunction() that accepts a list of functions with different return types as parameters. My goal is to have the return type of myMainFunction be determined by the return types of the functions passed to it ...

The functionality of updating the logo in the browser tabs is not functioning as expected in Vue.js 3

This is the code from my index.html: <!DOCTYPE html> <html lang=""> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE ...

Create an asynchronous method within an object-oriented programming (OOP) class

Presenting my Activity class. export class Activity { _name: string _goIn: boolean constructor(name: string) { this._name = name; this._goIn = false; } isGoIn() { return this._goIn; } setGoIn() { // instructions to asyn ...

Using NodeJS, craft a Promise function that implements Sequelize functionality

I'm a newcomer to using Promise and I'm struggling with creating a Promise that incorporates a Sequelize function which already utilizes Promise. I'd like something along the lines of: var geojson = require(path.join(__dirname, 'lib&a ...

What could be causing my AngularJS to malfunction on this particular website?

I am currently learning AngularJs and practicing some coding. However, I am facing an issue where the javascript code does not work when I run it on my browser (Chrome/IE). The "{{product.like}}" code is not functioning as expected. Is there any specific d ...

Every time an npm installation is attempted, the following error occurs: "npm ERR! Cannot read property 'resolve' of undefined."

Welcome Everyone! Currently, I am facing an issue on my dual boot system where Node and NPM were functioning smoothly on Windows 7. However, now that Windows 7 is not booting up, presumably due to hardware problems, I have resorted to using Windows 10. E ...

ThreeJs is known for effortlessly handling an abundance of vertices, far surpassing the number typically found

I came across this code snippet: function loadObject(filePath){ var loader = new THREE.OBJLoader(); loader.load( filePath, function ( object ) { child = object.children[0]; var geometry = new THREE.Geometry().fromBufferGeometry( ch ...

The jQuery autocomplete feature is malfunctioning, as it is unable to display any search

Creating a country list within an ajax call involves working with an array of objects: $.ajax({ url: '//maps.googleapis.com/maps/api/geocode/json?address=' + zipCode + '&region=AT', type: 'GET', dataType: &apo ...