Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

I can't preview the image using FileReader

I have a problem with filereader in reactjs, indeed I would like to preview the image after loading but the state manager does not change and the image doesn’t load

import React, { useState } from "react";
import { useSelector, useDispatch } from "react-redux";
import { isEmpty } from "../../Components/Utils";
import Img from "../../styles/assets/icons/img.svg";
import { createProduct } from "../../actions/product.action";
const AddProduct = () => {
  const [productText, setProductText] = useState("");
  const [productFile, setProductFile] = useState();
  const [productPrice, setProductPrice] = useState(0);
  const [productImg, setProductImg] = useState("");
  const [isDownload, setIsDownload] = useState(false);
  const [preview, setPreview] = useState("");

  const categories = useSelector((state) => state.categoriesReducer);

  const dispatch = useDispatch();

  const handlePreviewImg = (e) => {
    const reader = new FileReader();

    reader.onLoad = () => {
      if (reader.readyState === 2) {
        setPreview(reader.result);
        setIsDownload(true);
      }
    };

    reader.readAsDataURL(e.target.files[0]);
    setProductFile(e.target.files[0]);
  };

then I try to record in the input file tag so that the upload can be taken into account

<div className="dashboard__categories__form__picture add__product__picture">
            <input
              type="file"
              name="product"
              id="file"
              accept=".jpg, .jpeg, .png"
              className="inputfile"
              onChange={handlePreviewImg}
            />
            <label htmlFor="file">
              {!isDownload ? (
                <img src={Img} alt="icons" />
              ) : (
                <img src={preview} alt="categorie-pic" />
              )}
            </label>
          </div>

What is the problem? please help

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

I believe you don’t need to use FileReader.

Maybe you can use URL.createObjectURL

const handlePreviewImg = (e) => {
  const blobUrl = URL.createObjectURL(e.target.files[0]);
  setPreview(blobUrl);
}

createObjectURL may cause memory leak so you should read the document.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading