[vue.js] Error in API communication through store.dispatch in forEach statement

Asked 1 years ago, Updated 1 years ago, 313 views

We are developing a function to call an external API through the vue.js language as described in the title.

As I developed it, I have to implement the following behavior, but I am inquiring because I keep getting errors when I call the API in the forEach statement.

[Flow Chart]
1) API-1 call (return value: array) 
2) Execute the received array value forEach statement
3) Invoke API-2 with the information in the array value as a parameter

The error message is as follows.

JsonToExcelAll > catch :  TypeError: **Cannot read properties of undefined (reading '$store')**
    at eval (d:\3.0\src\components\SideListContentsTable.vue?c027:697:1)
    at Array.forEach (<anonymous>)
    at eval (webpack-internal:///849:694:18) {stack: 'TypeError: Cannot read properties of undefine…
    at eval (webpack-internal:///849:694:18)', message: 'Cannot read properties of undefined (reading '$store')'}

Calling API-2 outside the forEach statement works fine... Please give me an answer as to why...ㅠ<

[Add Source]

parseJsonToExcel2 (getTabInfo, getDongInfo) { // Excel download function

const self = this
this.json_to_excel = []

this.$store.dispatch('postSystemInfo', {  // API-1
        header: {
          cmd: '1'
        }
      }).then((data) => {

        if (data.result.status == '000' && data.header.cmd == '2') {

          _.forEach(_.orderBy(data.data.list, ['dong', 'ho'], ['asc', 'asc']), function (dong, i) { 

            arr_dong.push(dong) // contained in this information array

          })

          // I want to throw parameters using the same information of the array value as it is in the for statement
          // Calling API-2 in here error...
          arr_dong.forEach(function (value, index) { 
            // // console.log('TEST ====>> dong : ', value + " / i : " + index)
          })

          this.$store.dispatch('postDeviceStatus', { // API-2
            header: { cmd: '1' }, data: { dong: arr_dong[0], floor: 'all', line: 'all' }
          }).then((data) => {

            _.forEach(_.orderBy(data.data.data.list, ['dong', 'ho'], ['asc', 'asc']), function (data, pos) {

              getDong = data.dong
              getHo = data.ho
              getComm = data.comm

              _.forEach(_.orderBy(data.devices, ['uid'], ['asc']), function (v) {

                let json = {
                  'Comm Status': getComm,
                  'Device ID': v.uid,
                  'Device Status': v.status,
                }

                self.json_to_excel.push(json)

              })

            })

            if (!_.isEmpty(this.json_to_excel)) {
              var worksheetByJson = XLSX.utils.json_to_sheet(this.json_to_excel);
              var book = XLSX.utils.book_new();
              XLSX.utils.book_append_sheet(book, worksheetByJson, getDong + "동");
              XLSX.writeFile(book, '상세_' + moment().format('YYYYMMDDHHmmss') + '.xlsx');
            }

          })

        } } else {
          self.$store.commit('setAlertActive', { flag: true, msg: data.result.message })
        }

      }).catch((e) => {
        console.log('JsonToExcelAll > catch : ', e)
      })

foreach javascript

2022-11-18 03:59

1 Answers

arr_dong.forEach(function (value, index) { 
  // Here
})

// // API-2
this.$store.dispatch('postDeviceStatus', {
  header: { cmd: '1' }, data: { dong: arr_dong[0], floor: 'all', line: 'all' }
}).then((data) => {

API-2 refers to this, but if you put this code in here as it is, it is a simple reference error that occurs because this points to different things. Because within a function, this becomes the object that owns that function.

Simply put:

arr_dong.forEach(function (value, index) { 
  this.$store.dispatch('postDeviceStatus', { // API-2
    header: { cmd: '1' }, data: { dong: arr_dong[0], floor: 'all', line: 'all' }
  })... // Omit
})

Because the function you provided in Array.forEach() is an anonymous function, this becomes the global object of the browser, window. Anonymous functions are owned by a global object in the JavaScript executable. And window doesn't have a $store right?

There is an exception, but the arrow function does not change the scope of this. Please refer to the example below.

let obj = {
  executeMe() {
    setTimeout(function() {
      console.log('function this:', this);
    }, 100);

    setTimeout(() => {
      console.log('arrow this', this);
    }, 100);
  }
};

obj.executeMe();
// // function this: Window ...
// // arrow this: Object ...


2022-11-18 13:52

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.