Home > Blockchain >  Argument of type 'string' is not assignable to parameter of type 'Blob'
Argument of type 'string' is not assignable to parameter of type 'Blob'

Time:07-18

So I am having this problem.

import React, { useState } from "react";

const ImageInput: React.FC = () => {
  const [image, setImage] = useState("");
  let reader = new FileReader();
  reader.readAsDataURL(image);

  const handleUpload = (e: React.ChangeEvent<HTMLInputElement>) => {
    const imageValue = e.target.value;

    setImage(imageValue);
  };

  return (
    <input onChange={handleUpload} type="file" multiple={false} value={image} />
  );
};

export default ImageInput;

I am using React with TypeScript and I'm trying to make an image upload component but it is giving me this error. I've tried researching "Blobs" but no joy. I am getting the error in the readAsDataURL.

CodePudding user response:

The reader will be defined and executed on each render of the component. This seems off, it should rather happen inside a function.

As input for the readAsDataUrl one should not use a string, as TypeScript already complained, given the documentation, the input is a File or a Blob. Which can be retrieved directly from the input component. (Source: MDN)

For reference: "[..] a blob is a representation of immutable data, which can be read as text or binary" (Source: MDN)

Based on the above two links your component could look like this (note: image is currently unused):

import React, { useState, createRef } from "react";

const ImageInput: React.FC = () => {
  // create a ref to keep a reference to a DOM element, in this case the input
  const imagesUpload = createRef<HTMLInputElement>();
  const [image, setImage] = useState<string | ArrayBuffer | null>(null);

  const handleUpload = (e: React.ChangeEvent<HTMLInputElement>) => {
    // get the file which was uploaded
    const file = imagesUpload?.current?.files?.[0];

    if (file) {
      const reader = new FileReader();
      reader.addEventListener("load", function () {
        // convert image file to base64 string
        setImage(reader.result)
      }, false);
      reader.readAsDataURL(file);
    }
  };

  return (
    <input ref={imagesUpload} onChange={handleUpload} type="file" multiple={false} />
  );
};

export default ImageInput;
  • Related