0

I'm trying to set a state variable inside a function, but it doesn't get set immediately.

It eventually gets set, but I want to interact with the data inside the function as soon as the state is set.

code:

  const [addresses,setAddresses] = useState<any[]>([]);

  const fetchData = async () =>{

    try{

      const addresses = await fetchAddresses(data);
      setAddresses(addresses);
      console.log(addresses)
      
      //code that interacts with addresses state variable

    } 
    catch(err){
      console.log(err);
    }

  }

 useEffect(()=>{
   if(emptyArray){
     fetchData();
   }
 },[]);

Any help is appreciated, thanks.

jalapina
  • 3,962
  • 3
  • 12
  • 19
  • I don't think you should be using the same variable name `addresses` for both the state and the result of `fetchAddresses`. If you directly want to access `addresses`, use the one from the result of the fetch and update your state at the end of your business logic. – Fatih Aktaş Jul 07 '22 at 09:04

2 Answers2

1

You can not expect to update state and immediately after that to access that new state using exposed state from hook. That is because state update is async and state itself is being accessed from closure - meaning that value of addresses is retrieved from closure, and closure will be recreated only after element rerenders. Meaning that only in next iteration(aka next function call) you will get updated state(fresh value from closure). If you in some case need new sate immediately after you update, then you will need to preserve it in temp variable and use that variable as "state access", for example:

const newState = {...};
setState(newState);
... and later in code you will refer to state using `newState`, and not the `state`
Milos Pavlovic
  • 1,355
  • 1
  • 2
  • 7
0

I used a useEffect hook that gets called when my state is set and that worked for me

 const [addresses,setAddresses] = useState<any[]>([]);

 const fetchData = async () =>{

    try{

      const addressesArray = await fetchAddresses(data);
      setAddresses(addressesArray);
      
    } 
    catch(err){
      console.log(err);
    }

  }

 const OtherFunc = () =>{
  //do some code here with my state veriable
 }

 useEffect(()=>{
   if(condition){
     OtherFunc();
   }
 },[addresses]);


 useEffect(()=>{
   if(condition){
     fetchData();
   }
 },[]);

jalapina
  • 3,962
  • 3
  • 12
  • 19