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 variables outside of the computed property scope, and scope here means the function that starts with {
and ends with }
. You can use a method, watcher, or setter to overcome this issue.
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 to trigger a watcher. 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 arrays fruits
, and foods
, but both dependencies may change together. As a result, the computed will be executed once, but the incrementation to compares
happen twice. 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.