KaranManral
KaranManral

Reputation: 694

Vue.js updated() keeps on updating infinite times?

I had a simple vue component in which I am fetching a question from Database in beforeMounnt() method but after making some changes I wanted to reload the currentQuestion data in my state and its's working fine But the updated method keeps on fetching the new state from the state which is a performance pitfall as we know, can anyone tell me why this is happening ?

Before Mounted Method

  async beforeMount() {
        try {
            const res = await axios.get(`/question/${this.questionId}`);
            this.currentQuestion = { ...res.data };
        } catch (err) {
            this.error = err;
        }
    },

Data In Vue.js

 data() {
        return {
            error: "",
            success: "",
            currentQuestion: {},
            newChoiceDescription: "",
            totalChoices: 0
        };
    },

Update method

 updated() {
        console.log("Changing state");
        const res = axios
            .get(`/question/${this.questionId}`)
            .then(res => {
                // this.currentQuestion = res.data;
            })
            .catch(err => {
                this.error = err;
            });
    },

Upvotes: 0

Views: 52

Answers (1)

RoboKozo
RoboKozo

Reputation: 5062

The reason is because your updated() is causing an update to happen... which triggers the update

The official docs warn against doing this, check it out here: https://v3.vuejs.org/api/options-lifecycle-hooks.html#updated

Try using a watch on the questionId instead

Upvotes: 1

Related Questions