2

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.

Herbert IN
  • 59
  • 8
  • 1
    Setting state in React is asynchronous, just because `setGetCode` has been called, doesn't mean that `GetCode` is equal to the new value (yet) – DBS Jun 10 '22 at 13:00
  • Yes that I get it , but what is the solution for this case, how could I get the value, after call the function? – Herbert IN Jun 10 '22 at 13:04
  • 1
    How is your function being called? It must be pretty soon after the API response to be seeing this result, it might be possible to change the component to use a `useEffect` to wait for the `GetCode` change, but that would depend on the rest of the component. – DBS Jun 10 '22 at 13:18
  • I can't use the useffect because i'm using to get the last code of the database before insert a new row – Herbert IN Jun 22 '22 at 15:24

1 Answers1

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