If you have ever faced an error complaining about unexpected side effects while developing a Vue app, Then you have committed an anti-pattern. But don’t worry. This post gives you not one but three approaches to resolve this error, from easy to advanced.
Unexpected side effects happen when you modify Vue data properties inside computed property scope. To fix this, you may a method, a watcher, or a setter.
1. Calling a Method Inside the Computed Property
This is the most straightforward approach. In a nutshell, create a method as a proxy to manage side effects and invoke it inside the desired computed property.
2. Using Watchers but Carefully!
Not every recalculation of a computed value guarantees a change in the result so a watcher might stay untriggered. Considering this, you can use a watcher to manage side effects whenever the dependencies of a computed property or the result value are updated. But notice that these are two different flows of reactivity. In the previous example, you may watch for both fruits
, and foods
arrays, but if they change together, despite the incrementation to compares
variable which happens twice the computed property will be executed only once. So when using Watchers to handle side effects, be careful of dependencies and various scenarios that affect your application. I wouldn’t recommend using Watchers to manage side effects because it’s easy to make mistakes using this approach, especially if you haven’t mastered the subject of reactivity yet.
3. Benefitting from the Almighty Setter!
Many Vue developers are unfamiliar with computed setters that can be used to assign a value. This requires defining the computed property as an object with one getter and one setter function. Getter functions are invoked when there is a change in the dependency array, just like a regular computed. On the other hand, setter functions are invoked when the computed property is assigned a value using =
. Please see the example below. In this case, an animation triggers whenever an assignment happens, or in other words, the setter is invoked.
Conclusion
To sum up, whenever you face an error about unexpected side effects, you have updated a variable that is declared out of the computed property’s scope. Depending on your needs, you can benefit from a proxy method for all the side effects. You may also use a watcher to manage side effects when a value changes, but be careful about reactivity and the order of code execution in different situations. And lastly, you could use a computed set function to update all of the desired variables without any concern about facing the unexpected side effect error.