Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

112
Vistas
How can I make a part of code inside the function to run after the state updates or when it is not undefined in react native?

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?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

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" }]);
       }
    }
    
  };

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda