0

Array: newIndexes: [123,124];

Code:

  this.newIndexes.forEach((value, i) => {
            console.log('hi')
            console.log(value);
            let IndexToEdit = this.indexOfAddedFile + i;
            console.log(IndexToEdit);
            this.allData[parseInt(IndexToEdit)].ID = parseInt(value);
        });

Extra info: Im adding it to an empty array so the variable 'indexOfAddedFile' = 0. None of the console.log's want to run. I'm not getting any console errors.

I'll just paste the entire script tag down here, hope it helps!:

<script>
export default {
    props: ['selectedItem', 'index', 'opened', 'user'],

  data(){
    return{
      allData: [],
      allDataNew: [],
      uploadedItems: '',
      newIndexes: [],
      indexOfAddedFile: 0,
      filesSize: 0,
    }
  },

  watch: {


      // Kijkt of de geselecteerde shipment veranderd.
      // Zet de juiste data in t form.
    opened(){
      if (this.opened == true) {
        axios.get('/app/planningtool/files?SHIPMENTNUMBER=' + this.selectedItem.SHIPMENTNUMBER)
        .then(response => this.allData = response.data);
      }
    }
  },



  methods: {

    deleteFile(id, index, name){
      let r = confirm('Are you sure you want to delete this file?');

      if (r == true) {
        axios.post('/app/planningtool/files/delete?id=' + id);
        this.allData.splice(index, 1);
      }
    },

    saveFiles(e){
      this.indexOfAddedFile = this.allData.length;
      let fileList = e.target.files || e.dataTransfer.files;
      this.filesSize = 0;
      let formData = new FormData();
      let today = new Date();
      let date = today.getFullYear()+'-'+(today.getMonth()+1)+'-'+today.getDate();
      let time = today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();

Array.from(fileList).forEach((item, i) => {
        this.allDataNew.unshift({'Naam': item.name, 'Type': item.type, 'Datum': date, 'Tijd': time, 'Username': this.user[0][0].USERNAME, 'SHIPMENTNUMBER': this.selectedItem.SHIPMENTNUMBER, 'ID': 0});
        formData.append('file[]', fileList[i]);
        formData.append('name[]', fileList[i].name);
        formData.append('type[]', fileList[i].type);
        formData.append('size', i);
        console.log(fileList[i].size);
        this.filesSize = this.filesSize + fileList[i].size;
      });

        formData.append('SHIPMENTNUMBER', this.selectedItem.SHIPMENTNUMBER);
        formData.append('Username', this.user[0][0].USERNAME);
        formData.append('Datum', date);
        formData.append('Tijd', time);

        if(this.filesSize > 8388605){
          alert('The file(s) is/are too big. Upload canceled. Max upload size is 8,2MB.');

        }else {
          axios.post('/app/planningtool/files/upload',
          formData,
          {
          headers: {
              'Content-Type': 'multipart/form-data'
          }})
          .then(response => this.newIndexes = response.data);

          this.allData = this.allData.concat(this.allDataNew);

          console.log('hi');
          this.newIndexes.forEach((value, i) => {
            console.log('hi')
            console.log(value);
            let IndexToEdit = this.indexOfAddedFile + i;
            console.log(IndexToEdit);
            this.allData[parseInt(IndexToEdit)].ID = parseInt(value);
        });
        console.log('hi again');
    }

      },

    // Stuurt bericht naar parent om modal te sluiten.
    close(){
      this.$emit('closed');
    },

    // Submit form data.
    onSubmit(){
      this.$emit('planner-files-edited', this.form.data());
      this.form.submit('post', '/app/planningtool/edit');
      this.$emit('closed');
    },

  },
}
</script>
casper b
  • 35
  • 1
  • 6
  • are you getting any error message(s)? Can you probably post your whole ` – Kodiak Jul 29 '20 at 07:48
  • Nope no errors. It just seems to skip the forEach completely. – casper b Jul 29 '20 at 07:48
  • 1
    `newIndexes` is probably empty. can you please: `console.log(JSON.parse(JSON.stringify(this.newIndexes)));` **before** the `.forEach`? – briosheje Jul 29 '20 at 07:49
  • There's no reason for those `parseInt`s (unless `this.indexOfAddedFile` is a string or something, which seems unlikely), but that's not the problem. The best way to find out what's wrong here is to use the debugger built into your browser or IDE and set a breakpoint on both the `forEach` line and the first line within the callback, and examine your variables and properties when you hit those breakpoints. – T.J. Crowder Jul 29 '20 at 07:50
  • Sorry but to what does the this in there refer to? – sçuçu Jul 29 '20 at 07:50
  • I've added the entire script tag for more info – casper b Jul 29 '20 at 07:51
  • Is is possbile the newIndexes i sempty and stay empty once the control reaches your forEach code and runs it. If so it is correct that the function inside does not run even once. – sçuçu Jul 29 '20 at 07:53
  • You didn't wait for the API to provide the results, you would need to put the `forEach` inside then or need to use async-await – Piyush Jul 29 '20 at 07:53
  • @casperb just add `console.log(this.newIndexes)` right before you call the for each on it and see what's inside. Or put a debugger above to check manually – Devchris Jul 29 '20 at 07:53
  • `this.newIndexes` is being asynchronously populated inside `.then(response => this.newIndexes = response.data)`. The `forEach` code runs before the array is populated. You need to do it inside the `then(a => { //here })`. OR you'd have to use async await to mimic synchronous code. Please check the duplicates for more details. – adiga Jul 29 '20 at 07:54

1 Answers1

3

You need to run this forEach code block after the API request completes, so inside the then of your api call promise. That way you will be waiting for the async api request to complete and if it completes with success, probably an HTTP 200 or alike, you run your code to update the state array. Asynchronous processes like most remote api requests should be waited if you want to use their response.

You may also consider using a catch block to handle the error cases too.

else {
        axios.post('/app/planningtool/files/upload',
          formData,
          {
            headers: {
              'Content-Type': 'multipart/form-data'
            }
          })
          .then(response => {
             this.newIndexes = response.data

             this.newIndexes.forEach((value, i) => {
               console.log('hi')
               console.log(value);
               let IndexToEdit = this.indexOfAddedFile + i;
               console.log(IndexToEdit);
               this.allData[parseInt(IndexToEdit)].ID = parseInt(value);
             });

        });

        this.allData = this.allData.concat(this.allDataNew);
    }
casper b
  • 35
  • 1
  • 6
sçuçu
  • 2,960
  • 2
  • 33
  • 60