Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

115
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda