I'm using the useState() hook, and I've found that my app has a bug, because setting the value is asynchronous. So if I have code like this:
const [data, setData] = useState([])
useEffect(() => {
const getData = async () => {
const res = await fetchData()
console.log(data); // []
setData(res.data.hits);
console.log(res.data.hits); // Array full of objects
console.log(data); // Still []
}
getData()
}, [fetchData]);
How can I execute some specific logic only when the new state has actually been set?
You can use the useEffect hook:
useEffect(() => {
//your code
}, [data]);
That will trigger what is inside every time data changes.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With