Shopify Guy
Shopify Guy

Reputation: 43

How to insert custom properties to File object in react

I am working on file upload functionality , what I want to achieve when I select multiple files or single file I want to assign custom property to each File object custom property must be like percentage:0 to File object. I tried hard but didn't find any proper solution to resolve this issue. Could someone please help me how to resolve this issue .

Thanks

Code

  addManualAttachments = (event) => {
    let files = event.target.files

    const fileList = Array.from(files)

    if (fileList.length > 10) {
      Swal.fire('Warning !', 'Maximum files upload limit is 10', 'warning')
      return false
    }

    for (let i = 0; i < fileList.length; i++) {
      if (this.validateFile(fileList[i])) {
        this.setState((prevState) => {
          return {
            ...prevState,
            selectedFiles: this.uniqueFiles([...prevState.selectedFiles, fileList[i]]),
          }
        })
      }
    }
  }

Upvotes: 0

Views: 1971

Answers (1)

Jason Bellomy
Jason Bellomy

Reputation: 562

If it is a plain Javascript object, you can add the new property right to the file as you loop over it. Also, you can use a forEach loop and don't need a for loop:

addManualAttachments = (event) => {
  const files = Array.from(event.target.files);

  if (files.length > 10) {
    Swal.fire('Warning !', 'Maximum files upload limit is 10', 'warning')
    return false
  }

  files.forEach((file) => {
    if(this.validateFile(file)) {
      file.percentage = 0; // <-- This will add the new property to the object reference stored for that file object.
      this.setState((prevState) => {
        return {
          ...prevState,
          selectedFiles: this.uniqueFiles([...prevState.selectedFiles, file]),
        }
      });
    }
  });
}

Upvotes: 1

Related Questions