Search code examples
javascriptvue.jsmethodsresponsemount

VueJs Method is changing directly a response


I have a parent component and ı am making a query to backend in there, then with the help of the navbar and my activeView data in the parent component with on Clicks I render a new child page and pass a prop from my response with the help of v-if in vue. But one of the functions of the method is changing my prop in the parent component also IT CHANGES MY RESPONSE how can this be possible. This is the before mount of my child component:

beforeMount() {
    console.log(this.plansPropOrg);
    this.plansProp = this.plansPropOrg;
    this.tempPlan = this.plansProp.currentPlan;

    console.log(this.plansProp);
    this.propsToData();
}

the problematic function is propsToData when ı comment out here it is normal but ı have to call it.

And here is the my parent when ı make the query:

await axios.post("xxxxx/yyyyyyy").then(res => {
                console.log("heyyo");
                console.log(res);
                this.plansData = res.data.data;
                console.log(this.plansData);
            });

And here is the props to data, it is just translating boolean values to english. But in the response, (when this if is true) ı see the values as translations.

propsToData() {
        //TODO: Burdaki if' ifsubscriber olarak değişecel
        console.log("AAA");
        console.log(this.plansProp);
        if (this.plansProp.isSubscriber) {
            console.log("BBBBB");
            this.plansProp.currentPlan.analytics
                ? (this.plansProp.currentPlan.analytics = this.$t(
                      "settings.plans.active"
                  ))
                : (this.plansProp.currentPlan.analytics = this.$t(
                      "settings.plans.inactive"
                  ));
         }
   }

How can this be possible how can it change the response?


Solution

  • You're copying the response and the plansProp object by reference, meaning both objects are pointing to the same place in memory. When you change one of them, the other still points to the same place in memory, meaning when you retrieve it it's going to be the same object.

    You want to do either a shallow (Object.assign()) or a deep (JSON.parse(JSON.stringify())) copy, depending on how your object is structured.

    More info on that here https://www.javascripttutorial.net/object/3-ways-to-copy-objects-in-javascript/.