Ari Seyhun
Ari Seyhun

Reputation: 12511

Catching errors in computed properties in Vue

In VueJS I have a vuex store getter which may throw an error of type ErrorOne or ErrorTwo.

// myGetter.js
export class ErrorOne extends Error {}
export class ErrorTwo extends Error {}

export default () => {
    if (...) {
        throw new ErrorOne()
    }
    if (...) {
        throw new ErrorTwo()
    }
    return ...
}

And in a computed property in my Vue component I am using this getter but I want to handle these errors in a try catch block.

// MyComponent.vue
import { ErrorOne, ErrorTwo } from '.../myGetter'

export default {
    ...,
    data() {
        return {
            errorOne: false,
            errorTwo: false
        }
    },
    computed: {
        myGetterComputed() {
            try {
                const value = this.$store.getters['.../myGetter']
                this.errorOne = false            // Unexpected side effect
                this.errorTwo = false            // Unexpected side effect
                return value
            } catch (err) {
                switch (err.constructor) {
                    case ErrorOne:
                        this.errorOne = true     // Unexpected side effect
                        break
                    case ErrorTwo:
                        this.errorTwo = true     // Unexpected side effect
                        break
                 }
             }
         }
    }

}

But eslint tells me [eslint] Unexpected side effect in "myComputedGetter" computed property. [vue/no-side-effects-in-computed-properties].

What is the correct way to handle errors in Vue computed properties in my use case?

Should I move myGetterComputed to data and use a watch method to handle updates?

Upvotes: 0

Views: 3676

Answers (1)

Taro
Taro

Reputation: 126

If I am going straight to answer your question I can tell you that eslint is using this rule to warn you about an unintended side effect. As per the eslint-plugin-vue docs

It is considered a very bad practice to introduce side effects inside computed properties. It makes the code not predictable and hard to understand.

Basically what we need to remember is that computed properties are meant to be used when there's heavy logic associated to how we treat data inside templates. So you shouldn't be updating any properties/data inside a computed property logic.

I would like to help you further if you provide a more detailed example of what you're trying yo achieve

Upvotes: 4

Related Questions