I am trying to run a code in the async block after the state updates but I am getting undefined. I tried different ways like if the state is not null then this part of the code run but it doesn't work.
My code:
const fileMoveHandler = async () => {
const fileName = selectedImage.split("/").pop();
const newPath = FileSystem.documentDirectory + fileName;
setNewPathImage(newPath); //undefined
try {
await FileSystem.moveAsync({
from: selectedImage,
to: newPath,
});
} catch (err) {
console.log("Error:", err);
Alert.alert("Can't move this file.", "Try again!", [{ text: "Okay" }]);
}
};
const savePlaceHandler = () => {
fileMoveHandler();
console.log("newPathImage: ", newPathImage);
//here newPathImage is undefined
dispatch(placesActions.addPlace(titleValue, newPathImage));
props.navigation.goBack();
};
I want to run dispatch method after the state updates.
What changes should I make in my code so that it will only run if newPathImage is not undefined?
Should I try promise or something else?
You can use useEffect to execute dispatch when newPath changes
useEffect(() => {
if(newPathImage){
dispatch(placesActions.addPlace(titleValue, newPathImage));
}
}, [newPathImage]);
If you dont want it render everytime. You can put dispatch method in fileMoveHandler.
const fileMoveHandler = async () => {
const fileName = selectedImage.split("/").pop();
const newPath = FileSystem.documentDirectory + fileName;
setNewPathImage(newPath); //undefined
if(newPath){
dispatch(placesActions.addPlace(titleValue, newPath));
try {
await FileSystem.moveAsync({
from: selectedImage,
to: newPath,
});
} catch (err) {
console.log("Error:", err);
Alert.alert("Can't move this file.", "Try again!", [{ text:"Okay" }]);
}
}
};