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
CodePudding user response:
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.