I have the following function, and there is two Alerts. The first Alert shows that the settingsChangedRoute
is true
, so after setSettingsChanged(settingsChangedRoute)
; the settingsChanged
value should be true too, as I understand it. But it is false and I don't get why. Please help to fix it, as it should be true
.
const [settingsChanged, setSettingsChanged] = useState(false);
//...
const load = async () => {
if (!!(route?.params)) {
const settingsChangedRoute = route.params.settingsChanged;
Alert.alert(`settingsChangedRoute === ${settingsChangedRoute}`);
setSettingsChanged(settingsChangedRoute);
}
const savedMode = await AsyncStorage.getItem('mode');
if (!!savedMode) {
const savedBlocked = await AsyncStorage.getItem('blocked');
if (savedBlocked) {
setBlocked(JSON.parse(savedBlocked));
}
setMode(savedMode);
const savedTurn = await AsyncStorage.getItem('turn');
setTurn(savedTurn);
const savedFieldSize = await AsyncStorage.getItem('fieldSize');
const parcedFieldSize = JSON.parse(savedFieldSize);
setFieldSize(parcedFieldSize);
const savedDifficulty = await AsyncStorage.getItem('difficulty');
setDifficulty(savedDifficulty);
Alert.alert(`settingsChanged === ${settingsChanged}`);
if (settingsChanged) {
setInitialFieldState();
setSettingsChanged(false);
} else {
const fieldStateJSON = await AsyncStorage.getItem('fieldState');
if (!!fieldStateJSON) {
setFieldState(JSON.parse(fieldStateJSON));
}
}
} else {
setInitialFieldState();
}
}
CodePudding user response:
The useState() hook updates values asynchronously. So, even though you updated settingsChanged to true by the time the code execution reached to the second alert, the values are not changed yet. It is, therefore, advised to use useEffect hook.
Refer to this doc: https://reactjs.org/docs/hooks-effect.html
useEffect(()=>{
// write code that will execute after settingsChanged has been updated
},[settingsChanged])
If you need to just execute a code only when settingsChanged value is updated to true, you can simply add a condition inside useEffect
useEffect(()=>{
if(settingsChanged) {
// write code that will execute after settingsChanged has been
// updated to true
}
},[settingsChanged])