Browse Source

Prevent duplicate state update when setting thumbnail

Now that thumbnail generation is synchronous using URL.createObjectURL,
we can set the thumbnail URL on the file object immediately. This saves
a state update, since `addThumbnail` previously would also trigger a
state update. That used to make sense, because thumbnails were generated
async using a FileReader, but it's not necessary anymore.
Renée Kooi 8 years ago
parent
commit
2f8d377fce
2 changed files with 9 additions and 16 deletions
  1. 4 16
      src/core/Core.js
  2. 5 0
      src/core/Utils.js

+ 4 - 16
src/core/Core.js

@@ -179,16 +179,16 @@ class Uppy {
       preview: file.preview
     }
 
+    if (fileTypeGeneral === 'image' && !isRemote) {
+      newFile.preview = Utils.getThumbnail(file)
+    }
+
     updatedFiles[fileID] = newFile
     this.setState({files: updatedFiles})
 
     this.bus.emit('file-added', fileID)
     this.log(`Added file: ${fileName}, ${fileID}, mime type: ${fileType}`)
 
-    if (fileTypeGeneral === 'image' && !isRemote) {
-      this.addThumbnail(newFile.id)
-    }
-
     if (this.opts.autoProceed) {
       this.upload()
         .catch((err) => {
@@ -206,18 +206,6 @@ class Uppy {
     this.log(`Removed file: ${fileID}`)
   }
 
-  addThumbnail (fileID) {
-    const file = this.getState().files[fileID]
-
-    const thumbnail = URL.createObjectURL(file.data)
-    const updatedFiles = Object.assign({}, this.getState().files)
-    const updatedFile = Object.assign({}, updatedFiles[fileID], {
-      preview: thumbnail
-    })
-    updatedFiles[fileID] = updatedFile
-    this.setState({files: updatedFiles})
-  }
-
   calculateProgress (data) {
     const fileID = data.id
     const updatedFiles = Object.assign({}, this.getState().files)

+ 5 - 0
src/core/Utils.js

@@ -166,6 +166,10 @@ function getFileNameAndExtension (fullFileName) {
   return [fileName, fileExt]
 }
 
+function getThumbnail (file) {
+  return URL.createObjectURL(file.data)
+}
+
 function supportsMediaRecorder () {
   return typeof MediaRecorder === 'function' && !!MediaRecorder.prototype &&
     typeof MediaRecorder.prototype.start === 'function'
@@ -393,6 +397,7 @@ module.exports = {
   truncateString,
   getFileTypeExtension,
   getFileType,
+  getThumbnail,
   secondsToTime,
   dataURItoBlob,
   dataURItoFile,