I'm trying to upload an image but can't setState to be reader.result

I’m trying to read a file and then set the state of imgSrc to be reader.result but for some reasons when I console log imgSrc I get an empty string or null.

let [imgSrc, setImgSrc] = useState();
let showFileName = (e) => {
    let uploadButton = document.getElementById("confirmUploadBtn");
    imgFile = e.target.files[0];
    let image = document.getElementById("profileImage");
    const reader = new FileReader();
    reader.onload = () => {
        // imgSrc = reader.result;
        let result = reader.result;
        setImgSrc(result);
        console.log(imgSrc);
        image.innerHTML = `<img src=${imgSrc} width="300px" height="300px" style="border-radius: 50%;" />`;
        uploadButton.textContent = "Save Photo";
    }
    if (imgFile) {
        reader.readAsDataURL(imgFile);
    }
    console.log(imgSrc);
}

50 thoughts on “I'm trying to upload an image but can't setState to be reader.result”

Leave a Comment