I have an app that fetches data from the API. There is no safe default value that I can assign to a piece of state, because the API may return any value. As a solution, I want to set an element of state to true
after completing the API call.
const [data, setData] = useState<any>()
const [dataLoaded, setDataLoaded] = useState(false)
useEffect(() => {
setDataLoaded(false)
Promise.resolve("myData").then(res => {
setData(res)
setDataLoaded(true)
})
}
}, [])
Will the following code, is it guaranteed that dataLoaded
will be set to true only after data
is populated? I understand that I can't, for example, guarantee myself access the contents of data
in the call to setDataLoaded
, but does that mean that the state changes themselves can execute in any order?
If not, how can I guarantee that it will be?'
I know that this guarantee does exist in class components, but I don't know if it does in hooks, especially if it's happening inside a promise.