Created
February 13, 2020 19:25
-
-
Save andycarrell/ae28fd156470a0005e80fbea201ab68e to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function useFileReadAsDataURL(file) { | |
const [dataURL, setDataURL] = React.useState(""); | |
const fileReaderRef = React.useRef(new FileReader()); | |
React.useEffect(() => { | |
const fileReader = fileReaderRef.current; | |
const setResult = () => { | |
setDataURL(fileReader.result); | |
}; | |
if (file && file instanceof File) { | |
fileReader.readAsDataURL(file); | |
} | |
fileReader.addEventListener("load", setResult, false); | |
return () => { | |
fileReader.removeEventListener("load", setResult, false); | |
}; | |
}, [file]); | |
return dataURL; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment