What is the best way to separate axios functions and components in Vue3?

In my opinion, it's more efficient to separate the axios commands from the vue components. This is how I structured my directories:

src
  api
    - products.js
  components
    - Products.vue

products.js

import axios from 'axios';

const listProducts = () => {
  const headers = { "Content-Type": "application/json" };
  let url = "http://localhost:8001/api/v1/products";
  const response = axios.get(url, headers);
  return response.data
}

export default {
  listProducts,
}

Products.vue:

<template>
  <div>{{ products }}</div>
</template>

<script>
import { listProducts } from "@/api/products.js"

export default {
  data () {
    return {
      products: {},
    }
  },
  created() {
    this.fetchProducts();
  },
  methods: {
     fetchProducts() {
       this.products = listProducts();
     }
   }
}
</script>

However, I'm facing an issue where this.products is undefined. I've experimented with async and await, but to no avail.

What would be the best practice in vue3?

Answer №1

When using axios.get(), it is important to note that it returns a Promise. Therefore, the variable response in the next line actually represents a Promise and not the Axios response itself:

const listProducts = () => {
  ⋮
  const response = axios.get(url, headers);
  return response.data // ❌ `response` is a `Promise`
}

To correctly obtain the response, you need to await the outcome of the axios.get() function call:

                       👇
const listProducts = async () => {
  ⋮                   👇
  const response = await axios.get(url, headers);
  return response.data
}

Furthermore, the updated listProducts() function now returns a Promise due to its async nature. Therefore, your component must also await the result of listProducts():

// Products.vue
export default {
  ⋮
  methods: {
       👇
     async getProducts() {
                         👇
       this.products = await listProducts();
     }
   }
}

See the demo here

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

Unsynchronized AJAX POST requests fail to function effectively

I am encountering an issue with an AJAX call that I am using to log in a user. Here is the code: function loginUser() { var xmlhttp; if(window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp = new XMLHttpRequest() ...

Strange actions observed in AJAX POST request

This code snippet functions perfectly when I set a breakpoint in the backend and allow the value to be zero before continuing with the rest of the code. However, if I don't set a breakpoint and let it run, the value will become 2 and cause a break in ...

"Using ng-include with ng-show doesn't seem to be functioning properly

I am facing an issue with my Angular app where the template is getting too large. I would like to split it and utilize the ng-include directive, but I am struggling to get it to work properly. current state of template.html <div class="edit-ob ...

Performing multiple SQL queries in a for loop using Node.js and Express

After submitting a Post form, I receive a req.body containing multiple values in the following format: console.log(req.body) { productid:[1, 2, 3] qty: [3, 5, 6] } I'm trying to implement a for loop to use these values in SQL queries. However, I e ...

What is the proper way to create a regex pattern that specifies 'without any spaces'?

I need assistance in creating a regex expression that specifies "and NO whitespaces". I have to incorporate this into the following if statement shown below: $('#postcode').blur(function(){ var postcode = $(this), val = postcode.val(); ...

How to troubleshoot NodeJS errors when piping data from tar packing to webhdfs

I am currently in the process of developing a node application that utilizes Hadoop as a long-term storage solution for data when one of my services is not operational. To optimize efficiency and minimize processing time due to anticipated high transfer vo ...

Learn how to simultaneously play two audio files using the same identifier in JavaScript

I'm facing an issue with two audio files that have a progress bar and both have the same ID: <audio id="player" src="<?=base_url('mp3/'.$rec->file)?>"></audio> </p> ...

"Is it possible to include a query in a reducer with

Hey, how can I implement this inside a reducer to modify the state's value? doc = { id:"zf123ada123ad", name:"examp", subdoc:{ name:"subdoc examp", subsubdoc:[{ id:"zcgsdf123zaar21", subsubsubdoc:[{ ...

Express - An error occurred: Unable to access the property 'prototype' as it is undefined in the file request.js on line 31

My time has been consumed trying to troubleshoot this issue, yet I am puzzled by its origin and the reason behind this error. I am in the process of creating a basic website to hone my skills in React and have been attempting to retrieve data from Riot&ap ...

Contrasting {} and {} as any in TypeScript

Seeking clarity on TypeScript, what sets apart (foo and foo2) from (foo3 and foo4)? (foo and foo2) as well as (foo3 and foo4) produce identical results, yet during compilation, a red underline appears under foo2 and foo3. https://i.stack.imgur.com/lWaHc. ...

Receive the outcome once the form is submitted

Can someone provide quick assistance? I am looking to allow users to upload a CSV file for me to parse and analyze. Once the processing is done, I need to display the results back to the users. While uploading the file, I also need to ensure that the file ...

Troubleshooting problems with local references in an Angular date picker

I am currently working with an Angular date picker component and trying to access its values using a local reference. Unfortunately, when I attempt to console log the local reference, it returns undefined. The datepicker, function, and trigger are provid ...

Querying a subarray in MongoDB

Here is a document I have: { "_id" : "someId", "name" : "myTeam", "team" : [ { "entity" : "size", "value" : 14 }, { "entity" : "returns", ...

Describing how to assign multiple variables in a VUEX mutation

store.js import Vue from 'vue'; import Vuex from 'vuex'; import userStore from './user/userStore.js'; import VuexPersist from "vuex-persistedstate"; Vue.use(Vuex) const debug = process.env.NODE_ENV != ...

Submit Button Field - HTML ButtonFor

Being relatively new to MVC Razor and web development, both front-end and back-end, I'm in need of a button that can send a stored value to the controller/model. I attempted to mimic the functionality of Html.TextBoxFor by giving it attributes similar ...

Can anyone tell me how to retrieve the value of {{org}} in this situation?

<head> <title>My Unique Page</title> </head> <body> <input type="text" ng-model="selectedOrg" ng-show="!isSuperAdmin" readonly /> <select id="nameOrg" ng-model="selectedOrg" ng-cha ...

I'm feeling lost - I'm trying to use axios for a delete request, but I'm having trouble troubleshooting with req.params.id and using mongodb as the

I'm currently working on a function that deletes a post from the local MongoDB database. I've tested the code using Postman and it's functioning correctly. However, when trying to execute it on the frontend using Axios, there seems to be an ...

Is the navigation component's loss of properties due to a React router error?

After implementing react router for the first time, I noticed that the props passed to my nav component get lost once a new route is rendered. It's like the items in the cart are disappearing when I click checkout, but reappear correctly when I go bac ...

Auto play feature malfunctioning in Onsen-UI Carousel attribute settings

When utilizing onsen UI in my mobile web application, I encountered an issue with the autoplay property not functioning properly within the carousel. <ons-page> <ons-toolbar> <div class="left"> <ons-toolbar-button on ...

Using addClass and removeClass functions in JQuery when selecting a radio button

I am facing an issue with my radio buttons being displayed as images. When a picture (radio button) is selected, I want the other pictures to become hidden. To achieve this, I plan to add a class to the checked picture and then add another class to the unc ...