Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Computed property needs to wait for async data

Tags:

vue.js

export default {
  data() {
    return {
      projects: []
    }
  },
  mounted() {
    axios.get('...')
         .then(({ data } => this.projects = data)
  },
  computed: {
    personalProjects() {
          return this.projects.filter(...)
      },

      commercialProjects() {
          return this.projects.filter(...)
      }
  }
}

The computed properties need to wait for projects to be fetched from the server before setting the data. What's the proper way to do this?

I tried this:

watch: {
      projects() {
          this.personalProjects = this.projects.filter(project => project.type === 'personal')
          this.commercialProjects = this.projects.filter(project => project.type === 'commercial')
      }
  },

but I got an error message: Computed property "personalProjects" was assigned to but it has no setter.

Should I set personalProjects and commercialProjects in data() instead?

like image 557
Joshua Leung Avatar asked Oct 28 '25 17:10

Joshua Leung


1 Answers

What you are currently doing is the correct approach. Computed properties are reactive, derived, properties. They will reactively update whenever projects is updated by the data request.

In essence, your component's logic starts off with no projects, [] and if anyone asks for personal or commercial projects they are given the correct result: there are none of either, [].

However, whenever the component is mounted, it starts the process of loading the actual projects and whenever it's done, the whole dependency graph of projects will be reactively updated meaning personalProjects will be provide the correct result.

like image 164
zero298 Avatar answered Oct 31 '25 09:10

zero298