Send a photo to the bank through onChange on React?

Asked

Viewed 28 times

-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"/>
               </>

    )
};        

1 answer

0


The method useState is asynchronous which means it takes time to run and when you give the console.log in the variable photoPortifolio she is not yet ready with the value.

Recommended to check the value of a status whenever it is changed is to use the useEffect which is also a React hook.

Add this hook to your code:

useEffect(() => { console.log(fotoPortifolio); }, [photoPortifolio])

So every time the value of photoPortfolio is changed, the useEffect hook will be called.

I hope it helps.

  • Thanks, a useEffect question allows you to check only one example variable: useEffect(() => {console.log(${fotoPortfolio} e ${props.id} ); } [photoPortifolio])

  • 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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.