1

I'm using react native without expo, when trying to set a value with UseState it doesn't set immediately, and I can't get the values ​​in another function.

const [gridData, setGridData] = useState([]);

useEffect(() => {
        getGridApi().then((response)=>{
            setGridData(response);
            pressed('Mon', 0);
        })
    
}, []);

const pressed = async (category, index) => {
    console.log(gridData); // empty
}

How can I make it wait to set and then call the function pressed()

Leoh
  • 642
  • 2
  • 17
  • 41
  • refer to https://stackoverflow.com/questions/54119678/is-usestate-synchronous , you can use another useEffect. – devd Aug 09 '20 at 14:02

2 Answers2

1

you can use this package or you can your own custom hook for this. unfortunately react don't provide useState With Callback functionality

Example:

import useStateWithCallback from 'use-state-with-callback';

const App = () => {
  const [count, setCount] = useStateWithCallback(0, count => {
    if (count > 1) {
      console.log('Threshold of over 1 reached.');
    } else {
      console.log('No threshold reached.');
    }
  });
 
  return (
    <div>
      <p>{count}</p>
 
      <button type="button" onClick={() => setCount(count + 1)}>
        Increase
      </button>
    </div>
  );
};
1

Cioa, unfortunately with hooks, setting state is async and you cannot get the last value in this way. But you can use another useEffect hook to retrieve any changes of state variable.

Try this:

useEffect(() => {
   console.log(gridData);  // this shows the last value of gridData setted by the other useEffect
}, [gridData]);

But pay attention: this useEffect I worte will be triggered every time gridData changes his value!

Giovanni Esposito
  • 10,696
  • 1
  • 14
  • 30