data() variable refuses to update when set inside nested functions

I am very new to VUE so please forgive if my terminology is not correct.

I am trying to set a variable which is defined in the script tag "data()" function.

I am trying to set a new value for a variable defined in data() from inside the "created()" lifecycle event. This works fine if done at the root level, but i need to do it within 2 nested calls as shown below and it will not work when nested inside the function calls:

app.vue

<template>
  
  <div class="container">
  
    <Button @btn-click="providerPicked" id="current-provider" :text="'Current Provider: ' + currentProvider" />


  </div>  
 
</template>


<script>
import { ZOHO } from "./assets/ZohoEmbededAppSDK.min.js";
import Button from './components/Button'

export default {
  name: 'App',
  components: {
    Button,
  },
  data() {
    return{
      currentProvider: 'x'
    }
  },
  created() {
    console.log("CREATED HOOK")
    ZOHO.embeddedApp.on("PageLoad",function(data)
      {
        console.log(data);
        //Custom Bussiness logic goes here
        let entity = data.Entity;
        let recordID = data.EntityId[0];

      ZOHO.CRM.API.getRecord({Entity:entity,RecordID:recordID})
        .then(function(data){
          console.log(data.data[0])
          console.log(data.data[0].name)
            //THIS DOES NOT WORK - variable still comes back 'x' in template, notice this is nested twice.
            this.currentProvider = data.data[0].name;
        });

      });
      
      ZOHO.embeddedApp.init();

      //THIS DOES WORK - SETS VAR TO "reee" in template, notice this is not nested
      this.currentProvider = "reee"
      
     
  }
  
}
</script>



>Solution :

Use arrow functions instead of anonymous functions.

Arrow functions do not bind this, and thus this will refer to the outer scope.

created() {
  console.log("CREATED HOOK")
  ZOHO.embeddedApp.on("PageLoad", (data) => {
    console.log(data);
    //Custom Bussiness logic goes here
    let entity = data.Entity;
    let recordID = data.EntityId[0];

    ZOHO.CRM.API.getRecord({ Entity: entity, RecordID: recordID })
      .then((data) => {
        console.log(data.data[0])
        console.log(data.data[0].name)
        //THIS DOES NOT WORK - variable still comes back 'x' in template, notice this is nested twice.
        this.currentProvider = data.data[0].name;
      });

  });

  ZOHO.embeddedApp.init();

  //THIS DOES WORK - SETS VAR TO "reee" in template, notice this is not nested
  this.currentProvider = "reee"
}

Leave a Reply