Search code examples
vue.jsvuejs2vue-componentcomputed-properties

Computed property not triggered (add to Set)


Disclaimer: new to javascript

I was just trying to trace all the current errors within a component in the following way, but I do not get what I am doing wrong. My errors set is updated each time the username changes, that said, my computed property displayErrors based on errors Set should also change:

Html component

<ol v-if="displayErrors">
  <li v-for="e in errors" v-bind:key="e">
    {{ e }}
  </li>
<ol>

Data

data: function () {
    return {
      username: "",
      errors: new Set(),
    }
  }

Watchers and methods

watch: {
    username: function (username) {
      this.checkUsernameAvailability(username)
    }
  },
  methods: {
    async checkUsernameAvailability(username) {
      const errorCode = 'usernameNotAvailable'

      try {

        const response = await this.$apollo.query({ query: GET_USERS_QUERY })
        const users = response.data.users

        const usernames = users.map((user) => { return user.username })
        
        if (usernames.includes(username)) {
          this.errors.add(errorCode)
        } else {
          this.errors.delete(errorCode)
        }
        
        // trying to force the computed property
        this.$forceUpdate()

      } catch (error) {
        console.log(error)
        return false
      }
    }
  }

Computed property

computed: {
    displayErrors: function() {
      console.log('triggered', this.errors.size)
      return this.errors.size > 0
    }
  }

Thanks in advance!


Solution

  • Set cannot be observed by Vue, only plain objects.

    The docs for the data property explain this (which also applies to computed properties):

    The data object for the Vue instance. Vue will recursively convert its properties into getter/setters to make it "reactive". The object must be plain: native objects such as browser API objects and prototype properties are ignored. A rule of thumb is that data should just be data - it is not recommended to observe objects with their own stateful behavior.

    You should use an array to store the list of errors.