-1
I am converting the photo to Base64 and displaying on the console, but the value in useState does not update immediately. It shows only from second attempt to upload the photo.
import React,{ useState } from 'react';
const Portfolio = () => {
const[fotoPortifolio, setFotoPortifolio] = useState({
foto: ""
})
function handleFoto(e){
var file = e.target.files[0],
reader = new FileReader();
reader.onloadend = function () {
var b64 = reader.result.replace(/^data:.+;base64,/, '');
setFotoPortifolio({...fotoPortifolio,
foto: b64
})};
reader.readAsDataURL(file);
addFoto()
}
function addFoto() {
console.log(fotoPortifolio)
}
return (
<>
<input name="foto" onChange={handleFoto} type='file' accept="image/png, image/jpeg"/>
</>
)
};
Thanks, a useEffect question allows you to check only one example variable: useEffect(() => {console.log(
${fotoPortfolio} e ${props.id}
); } [photoPortifolio])– Vitoria Silva
The hook useEffect will execute WHENEVER your dependencies are updated. Dependencies are what you pass as a parameter in its dependency array. In our example dependence is photoPortfolio then whenever this variable is updated useEffect will run. If you find that my reply helped you solve/understand your brand problem as a response please. Thank you
– Erik Garces Matos