Surprising non-synchronous operation within the computed property "vue/no-async-in-computed-properties" in Vue3

I am currently working on a Vue3 project and encountering an error when running it. Below is the complete code snippet that I am using. Can anyone assist me in resolving this issue? Thank you in advance.

<script>
import axios from 'axios';
export default {
  name: "RegisterView",
  data() {
    return {
      user: {
        username: "",
        password: "",
        email: "",
        phoneNumber: "",
        role: "",
      },
      role : []
    };
  },computed:{
    getRole(){
       axios.get('http://localhost:8080/api/role/get').then(res=>{
        this.role = res.data;
      })
      return [];
    }
  },
  methods: {
    register() {
      axios.post("http://localhost:8080/api/user/register", this.user).then((res) => {
        console.log(res.data);
      });
    },
  },
};
</script>
// Error  Unexpected asynchronous action in "getRole" computed property  vue/no-async-in-computed-properties

I have attempted to use async and await, but it seems like I may have implemented them incorrectly.

Answer №1

Make sure to execute that function within the created lifecycle hook :

import axios from 'axios';
export default {
  name: "RegisterView",
  data() {
    return {
      user: {
        username: "",
        password: "",
        email: "",
        phoneNumber: "",
        role: "",
      },
      role : []
    };
  },
   created(){
     this.fetchRole();
  },
  methods: {
    fetchRole(){
       axios.get('http://localhost:8080/api/role/get').then(res=>{
        this.role = res.data;
      }).catch(err=>{
          this.role = []
      })
    
    },
    register() {
      axios.post("http://localhost:8080/api/user/register", this.user).then((res) => {
        console.log(res.data);
      });
    },
  },
};

Answer №2

Utilizing GetRole involves utilizing promises, meaning it does not provide immediate results but comes with side-effects. This is frowned upon by the code quality checker as it can be considered dirty code.

If you require asynchronous computed properties, it is recommended to use asyncComputed instead. This allows for immediate value and automatic updating when promise resolution occurs. Check out this repository for Options API, or @vueuse/core for Composition API.

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

Why are the random colors blending into the image?

After watching a tutorial on the YouTube channel Online Tutorials titled "Change Image Color Vanilla JavaScript," I am confused as to why some random colors from the click event are overlapping the image instead of just changing the color of the cat's ...

Guidance on dividing children in an object into distinct arrays

So I have an interesting challenge while working on my project. I need help figuring out how to split a Javascript Object like the one below: { field1: { field2: { field3: "value 1", field4: "value 2" ...

Nested objects in the Vuex store

I am currently developing an app in Vue that involves working with objects containing nested objects. The issue I am facing is related to accessing the "name" attribute of the school object within the user object. Despite the "name" attribute having a valu ...

When a function inside React uses this.props, it won't trigger the corresponding function

I am currently developing a Checklist using React and MaterialUI that consists of two components. One component is responsible for managing the data, while the other component allows for editing the data. However, I have encountered an issue where the func ...

"Encountering an issue in Vue.js 3 where the property cannot be

Inside my Something.vue: <template> <p>{{ codes }}</p> </template> export default { data() { return { codes: 'test' } }, name: 'Functions', props: { msg: String }, setup() { this. ...

Controlling Node.js application with Electron app: initiating and terminating

I'm currently working on the functionality to control the start and stop of another node.js application within my electron app. So far, I've managed to successfully start the node application from bot.js by running npm start to launch the electr ...

I am looking to extract a specific value from my JSON file

I need to extract specific values from a JSON file. For example, if the JSON file contains id, name, and lastname, I am interested in extracting the id value. fs.readFile("user.json", function (err, data) { if (err) throw err; console.log(data. ...

barchart rendered in SVG without the use of any external libraries

Creating a stacked barchart with SVG and HTML without relying on any third-party library has been quite a challenge. Despite searching extensively online, I have not come across a single resource that demonstrates how to build a stacked bar chart using pla ...

A guide on showcasing individual data using database relationships or Eloquent in Laravel within my Vue component

I'm encountering an issue when trying to view a single article with database relationships using Vue.js and Laravel API. Can someone please assist me? Below is my code for fetching a single article: export default { data() { return { ...

Retrieving external response data within a nested $http request

Excuse me as I am new to working with AngularJS. I am trying to figure out how to properly handle a nested $http call in my code, $http({ method: 'GET', url: host1, params: { 'format': 'json', } }).then(function ...

The persistent Bulma dropdown glitch that refuses to close

In the project I'm working on, I have implemented a Bulma dropdown. While the dropdown functions correctly, I am facing an issue when adding multiple dropdowns in different columns with backend integration. When one dropdown is open and another is cli ...

Create a pop-up window within a single controller using Angular.js

I followed a tutorial to create this code. I am interested in learning how to utilize just one controller for generating the dialog box. Currently, I am using two controllers for this project. Any guidance or tips would be greatly appreciated. View my cod ...

Code containing insertAdjacentHTML() does not run as expected due to injection of script

I have a scenario in my application where I am sending a request from the client to a node.js server. The server responds with an HTML containing a script: app.post('/verify', cors(issue2options), async (req, res) => { let auth = await mon ...

Do not fetch data again after a re-render

My code is facing an issue where every time I click toggle, the Child component re-renders and triggers another API request. My goal is to fetch the data once and then keep using it even after subsequent re-renders. Check out the CodeSandbox here! functio ...

Submitting a form from a non-AngularJS application to an AngularJS app requires URL rewriting

I am facing a challenge with my AngularJS search application. The search box is located on a standard HTML page that is not part of the AngularJS framework. Here is how the input field looks: <form accept-charset="UTF-8" name="search" id="search" act ...

What is the preferred way to handle return values in a JQuery Ajax function - true or

Just a quick question about my AJAX function - should I include return statements in the code? Here's an example for reference: $.ajax({ type: 'POST', url: 'Application.cfc?method=runProcess', data: {'userID' ...

Ways to update a ViewComponent using Ajax in Asp.net Core 3.1

How can I make FavoriteComponent refresh when the "a" tag is clicked? Html : <div id="favorite-user"> @await Component.InvokeAsync("FavoriteComponent") </div> Action Html : <a id="add-fav" onclick="addfavorite('@pr ...

What is the procedure for collapsing a table row or grid?

Looking at this image, I'm trying to find a way to collapse the breakfast row. Any ideas on how I can collapse either the entire tr or with a div? ...

Sending information from an AngularJS selected item to an edit form

Currently, I am working on an add/edit form using angularJS. Within this project, there are two templates - one for displaying a list of items and another for the form itself. While adding new items works smoothly, I have encountered some challenges when i ...

It appears that Yarn is having trouble properly retrieving all the necessary files for a package

Recently, I encountered a strange issue in our project involving 3 microservices, all using the exceljs library. Two of the microservices successfully download all necessary files for this package through yarn. However, the third microservice is missing ...