0

I have an image uploader built from scratch in a React app. The image preview - made thanks to window.URL.createObjectURL() - only works the first time. I thought it was because of memory issue, so I added window.URL.revokeObjectURL() before each image change. It still does not work.

I've heard about MediaSource() api but I havn't found any exemple for images. What is wrong with this code?

export default function ImageUploader({id, onAdd, onRemove}) {
  const [preview, setPreview] = useState(null);

  const onAddImage = (file: File) => {
    window.URL.revokeObjectURL(preview);
    setPreview(window.URL.createObjectURL(file));
    onAdd(id, file);
  };
  const onRemoveImage = () => {
    window.URL.revokeObjectURL(preview);
    setPreview(null);
    onRemove(id);
  };

  return (
    <div>
      {preview ? <Preview src={preview} alt={id} /> : 
       <Icon icon="upload" />
      }
      <input
        type="file"
        accept="image/png, image/jpeg"
        onChange={(e) => onAddImage(e.target.files[0])}
      />
    </div>
  );
}
DoneDeal0
  • 5,273
  • 13
  • 55
  • 114
  • can you show your preview component? – Dark shadow Nov 08 '20 at 11:37
  • It's just an img tag: const Preview = styled.img` object-fit: cover; border-radius: 8px; `; The issue doesn't come from here. I've loggued preview, I can see it's not updated anymore after the first upload. – DoneDeal0 Nov 08 '20 at 11:46
  • Go through the code sandbox with minimal code similar to your's which is working fine. [link](https://codesandbox.io/s/hungry-wildflower-zclg2?file=/src/App.js) – Dark shadow Nov 08 '20 at 11:48
  • I've updated the sandbox with a complete code: https://codesandbox.io/s/red-tree-3kglr?file=/src/App.tsx it doesn't work here, when you drag'n'drop or simply click on "upload" more than once. – DoneDeal0 Nov 08 '20 at 12:05
  • I made few changes.Check your sandbox now. You missed to use the Preview component. [link](https://codesandbox.io/s/jolly-hoover-p09er?file=/src/App.js) – Dark shadow Nov 08 '20 at 12:15
  • It doesn't work if I drag'n'drop a file => remove it => try to drag'n'drop a file again. Also, Sorry, it seems I've copy/pasted your link instead of the actual complete code: https://codesandbox.io/s/snowy-firefly-zudde – DoneDeal0 Nov 08 '20 at 12:22
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/224280/discussion-between-dark-shadow-and-donedeal0). – Dark shadow Nov 08 '20 at 12:27
  • Desmond Hew found the solution, thanks a lot for your time and your help :)! – DoneDeal0 Nov 08 '20 at 12:44

1 Answers1

1

the input value not changing, so it wouldn't trigger the onChange function. You can use react useRef hooks api and assign to the input tag and clear the input value inside the onRemoveImage function.