Search code examples
vue.jsfilereadericalendar

'i is not defined' at FileReader.reader.onload VueJs


I cant execute a for loop nor a forEach in an array because its says that i is not defined

I have already tried to use a while, a for, a for each. Use i like a Vue data variable. I set that let self = this, because the scope changes within that reader.onload. and I know that the problem has to be with something like that.

<template>
  <div>
    <p>My File Selector: <file-select v-model="file"></file-select></p>
    <p v-if="file">{{file.name}}</p>
    <v-btn v-if="file" @click="importFile">Import</v-btn>
    <div id="fileContents">

    </div>
  </div>
</template>

<script>
  import icsToJson from 'ics-to-json'
  import FileSelect from './FileSelect.vue'

    export default {
        name: "ViewImport",
        components: {
          FileSelect
        },
        data(){
          return {
            file: null,
            fileInJson: null,
            categories: [],
            importExists: false,
            i
          }
        },
        created(){
            this.getCategories();
        },
        methods:{
            getCategories(){
              //this works 
           },
            importCreatingCategoryImport(){
              //code, this works 
            },
            doesImportExists(){
              for (var i = 0; i < this.categories.length; i++){
                if (this.categories[i].category.name === 'Import'){
                  this.importExists = true;
                  // break;
                }
              }
            },
            importFile(){
              if (this.file) {
                let reader = new FileReader();
                reader.readAsText(this.file, "UTF-8");
                let self = this;
                reader.onload = function (evt) { //If everything works 
                  //Changes the file to format JSON 
                  self.fileInJson = icsToJson(evt.target.result);

                  self.doesImportExists();//the loop

                  if (self.importExists){
                      console.log('Category exists');
                      //other method
                  }else{
                      console.log('not working'); //Because its in my BD
                    // self.importCreatingCategoryImport();
                  }

                };
                reader.onerror = function (evt) { //if it doesn't
                  document.getElementById("fileContents").innerHTML = "error reading file";
                }
              }
            },

        }
    }
</script>
//style commented


Solution

  • At the end I changed everything that was in my function inside the reader.onload but with self instead of this. Less readable, but working.