Is there a way to use reader.onload return to set my state in react?

Viewed 198

I'm trying to compress an image that was uploaded using the react-images-upload component. After the compression step I need to convert the file to Base64 and use it to update my state.

The code looks like this:

    const ImageUpload: React.FC<ImageUploadProps> = ({ setImgUrl }) => {
  const handleChange = useCallback(
    (files: File[], pictures: string[]) => {
      const options = {
        maxSizeMB: 1,
        useWebWorker: true
      }

      getBase64(files[0], options).then(function(result) {
        setImgUrl(result);
      });
    },
    [setImgUrl],
  );

  function getBase64(file: File, options: any){
    return new Promise(function(resolve, reject) {
      Compress(file, options).then(compressedBlob => {
        const convertedBlobFile = new File([compressedBlob], file.name, {type: file.type, lastModified: Date.now()})
        let reader = new FileReader();

        reader.readAsDataURL(convertedBlobFile);
        reader.onerror = reject;
        reader.onload = function() { resolve(reader.result); };
      })
  });
  }

But I'm facing problems in the setImgUrl(result) part... I keep receiving the error:

Argument of type 'unknown' is not assignable to parameter of type 'SetStateAction'. Type 'unknown' is not assignable to type '(prevState: string) => string'.

Can someone help me please?

1 Answers

I believe you can resolve the typescript error by casting the unknown result type to a string. The setImgUrl expects a string, but typescript does not know what is being returned in the promise from getBase64. So either type the getBase64 function to return a Promise<string> or simply use:

  getBase64(files[0], options).then(function(result) {
    setImgUrl(result as string);
  });
Related