My backAction function that's used in BackHandler event listener, uses a stage state for conditionals, but doesn't follow the state value updates when stage is updated by other components, as it gets stuck on the initial state value. and also return true and false don't do anything.
Expected Behavior:
If back button is pressed check current stage:
- If stage value is 1 then use
return falseto trigger back button default behavior and navigate back to the previous screen (with out the need to usenavigation.goBack()). - If stage value is more that 1 then just decrement the current stage
value by -1, and
return trueto stop the event bubbling.
Current Behavior:
Once back button is pressed:
- Uses and keeps using on each click
stageinitial value of 1 even if it's clear that other components changed it and used it's new value. return falsedoesn't even trigger the default behavior of the back button.
Code To Reproduce:
const [stage, setStage] = useState(1);
const backAction = async () => {
console.log(stage); // the bug: stage is always 1
if (stage === 1) {
console.log("Going back to previous screen!");
return false;
} else if (stage > 1) {
console.log("Setting stage back with -1");
await setStage((prevState) => prevState - 1);
return true;
}
return false;
};
useEffect(() => {
BackHandler.addEventListener("hardwareBackPress", backAction);
return () => BackHandler.removeEventListener("hardwareBackPress", backAction);
}, []);
Note: I've used the documentation pattern of assigning BackHandler.addEventListener to backHandler, and then using it in the events clean up as backHandler.remove(). didn't work either, but removed it here for the sake of simplicity.
Any help would be much appreciated.