Home > Software design >  Out of two functions, one can access variable's value, the other can't
Out of two functions, one can access variable's value, the other can't

Time:01-25

The data fetched from API contains two types of elements: cycles which are objects of few attributes, and last_update object, which contains ID and last_update: <date>.

I'm processing them in the following way:

<script>
  export default {
    data: () => ({
      jsonData: [],
      lastUpdate: '',
      items: [
        {
          action: 'mdi-calendar',
          active: false,
          items: [{ title: '' }],
          title: 'Last Update',
        }
      ]
    }),
    methods: {
      async parseData() {
        const response = await fetch("http://127.0.0.1:5012/api/v3/cycles", {
          headers: {
            "Content-Type": "application/json",
            "mode": "cors"
          }
        })
        let cycles = await response.json();
        if (cycles.length < 1) {
          console.error("Couldn't fetch cycles from DB...")
        }
        const last_update = cycles.filter(cycle => cycle.last_update);
        this.lastUpdate = last_update[0].last_update;
        console.log('Inside parseData:', this.lastUpdate);

        cycles = cycles.map(({source, revision, elements}) => ({source, revision, elements}));
        this.jsonData = cycles
      },
      setLastUpdate() {
        this.items[0].items.title = this.lastUpdate;
        console.log('Inside setLastUpdate:', this.items[0].items.title);
        console.log('Inside setLastUpdate:', this.lastUpdate);
      }
    },
    created() {
      this.parseData();
      this.setLastUpdate();
    }
  }
</script>

Now, the console shows the following outputs:

Inside setLastUpdate: <empty string>
Inside setLastUpdate: <empty string>
Inside parseData: 2023.01.24 08:44:32

The value gets read and updates the lastUpdate in data section. Why it can't be read by the setLastUpdate() function?

I was thinking that there may be something with async setting, so I made setLastUpdate() function async just for testing, but the asynchronous action in parseData() function only refers to fetching the data from API. After the data is there, all processing happens on the same set of data for both reading cycles and last_update.

How to refactor the code so that the lastUpdate is available for setLastUpdate() function and possibly update the data.items object?

CodePudding user response:

As per looking at the console statement, function setLastUpdate is calling before the parseData function. So, to make the lastUpdate property available for setLastUpdate, you need to call those functions asynchronously. You can create a single async function that will call both functions one by one and wait for the first to be executed. For example-

created() {
  this.init();
},

methods: {
  async init() {
    await this.parseData();
    await this.setLastUpdate();
  },
},

One more thing-

instead of-

this.items[0].items.title = this.lastUpdate;

It should be-

this.items[0].items[0].title = this.lastUpdate;

Because inner items is having an array of objects structure.

  • Related