lavantho0508
lavantho0508

Reputation: 155

Unexpected asynchronous action in "" computed property vue/no-async-in-computed-properties Vue3

I am developing my project with Vue3 , I am getting this error while running, here is my whole code . Can someone help me fix it. Thank you guys

<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 tried async and await , but it seems I got it wrong

Upvotes: 0

Views: 2333

Answers (2)

Boussadjra Brahim
Boussadjra Brahim

Reputation: 1

Try to run that call inside the created hook :

import axios from 'axios';
export default {
  name: "RegisterView",
  data() {
    return {
      user: {
        username: "",
        password: "",
        email: "",
        phoneNumber: "",
        role: "",
      },
      role : []
    };
  },
   created(){
     this.getRole():
  },
  methods: {
    getRole(){
       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);
      });
    },
  },
};

Upvotes: 1

Dimava
Dimava

Reputation: 10919

GetRole uses promises, meaning it doesn't have immediate value but has side-effects, which is considered to be dirty code by the linter (code quality checker)

If you need async computed, use asyncComputed instead, which has immediate value and gets updated of promise resolution automatically https://github.com/foxbenjaminfox/vue-async-computed for Options API, @vueuse/core for Composition API

Upvotes: 0

Related Questions