Search code examples
javascriptvue.jsvue-componentlodash

error Unexpected side effect in "allOptions" computed property vue/no-side-effects-in-computed-properties


I trying to just find the index of the answer in my array in the computed region of Vue js but I am getting an error that some Unexpected side effect has occured

code :-

<script>
import _ from "lodash";

export default {
  name: "QuestionBottom",
  props: {
    currentQuestion: Object,
    nextQuestion: Function,
    increment: Function,
  },
  data() {
    return {
      selectedIndex: null,
      correctIndex: null,
    };
  },
  // watch changes to the props
  watch: {
    currentQuestion() {
      this.selectedIndex = null;
    },
  },

  computed: {
    allOptions() {
      let allOptions = [
        ...this.currentQuestion.incorrect_answers,
        this.currentQuestion.correct_answer,
      ];

      console.log("array that is not shuffled is ", allOptions);
      allOptions = _.shuffle(allOptions);
      console.log("shuffled array is", allOptions);
      console.log("Corect ans is ", this.currentQuestion.correct_answer);

      // here is the error occurring
      this.correctIndex = allOptions.indexOf(
        this.currentQuestion.correct_answer
      );
      return allOptions;
    },
  },

  methods: {
    selectedAns(index) {
      this.selectedIndex = index;
      console.log("Selected answer index", this.selectedIndex);
    },
    submitAnswer() {
      let isCorrect = false;
      if (this.selectedIndex === this.correctIndex) {
        isCorrect = true;
      }

      this.increment(isCorrect);
    },
  },

  mounted() {
    // console.log(this.currentQuestion);
  },
};
</script>

I am fairly new in Vue.js. I don't know what is the reason that this unexpected behavior is occurring in the computed region to my array.


Solution

  • Vue does not like changing a data variable (correctIndex) inside a computed property (allOptions). I would put that part into a watched method. https://v2.vuejs.org/v2/guide/computed.html#Watchers

    computed: {
        allOptions() {
          let allOptions = [
            ...this.currentQuestion.incorrect_answers,
            this.currentQuestion.correct_answer,
          ];
    
          console.log("array that is not shuffled is ", allOptions);
          allOptions = _.shuffle(allOptions);
          console.log("shuffled array is", allOptions);
          console.log("Corect ans is ", this.currentQuestion.correct_answer);
          return allOptions;
        },
    
        watch: {
            allOptions() {
                this.correctIndex = allOptions.indexOf(this.currentQuestion.correct_answer);
            }
        }
    

    That way allOptions stays computed, and will do just it's thing (and nothing more) - but is watched. Everytime it changes, correctIndex will be updated accordingly.