Divy Patel
Divy Patel

Reputation: 31

How to send data in previous screen with help of goBack()?

How to send data in previous screen with help of goBack() ?

I tried already. For ex: this.props.navigation.navigate('Login', {name: this.state.name})

Upvotes: 1

Views: 43

Answers (1)

Jatin Bhuva
Jatin Bhuva

Reputation: 1874

If you simply want to pass data to the previous screen then the below works:

Parent screen:

const Parent = () => {
  const [data, setData] = useState("");
  let navigation = useNavigation();

  const onPress = () => {
    navigation.navigate('Second', { getData: (x)=>setData(x) }); //<---here you have to pass callback function
  };
  return (
    <View style={{ flex: 1 }}>
      <Button
        onPress={onPress}
        title="Add title here"
        color="#841584"
        disabled={false}
      />
      <Text>{data}</Text>
    </View>
  );
};

Child screen:

const Child = ({ route }) => {  //<------here need to take route 
  let navigation = useNavigation();
  const onPress = () => {
    let data = "John";
    route.params.getData(data);   //<-----this way to update.
    navigation.goBack();
  };
  return (
    <View style={{ flex: 1 }}>
      <Button
        onPress={onPress}
        title="Add title here"
        color="#841584"
        disabled={false}
      />
    </View>
  );
};

Upvotes: 0

Related Questions