Search code examples
javascriptreactjsuse-effectuse-state

Clicking twice to see the value - UseState - UseEffect React using Function Component


I'm having a newbie problem, I really read all the documentations about it, and have seen all the stackoverflow about this issue, and I still can't get it right.

I need to get a value from a const variable, that I'm seeting without clicking twice, I tried a million things and still can't make this happen.

    const [GetCode,setGetCode] = useState("");
     const GetCodeMI = () =>{
    Axios.get('http://localhost:3001/GetMICode',{ }).then((response)=>{

            // console.log(response.data[0].ZZE_CODIGO);
             setGetCode(response.data);
         
        });
 }   
  const  InsertInternalMov = () => {
    GetCodeMi2().then(()=>{
        console.log(GetCode[0]);
      })
  }

In this scenario the first time that I click on the function the value of GetCode it's undefined the second time it shows correclty. I need to get the value the first time I click, My head it still wraping around how react works.


Solution

    1. if you want to set value immediately, you can try to use React.useRef()
    2. setGetCode is asynchronous function