Kimako
Kimako

Reputation: 625

Passing data from one screen to another React-native

I'm trying to pass data from one screen to another.

My problem is that the first screen goes to a calendar, when I've finished to put the dates in the calendar, I submit and go back to the first screen, the problem is that the first screen doesn't reload when I go back to it, so the data is not loaded, I think.

First screen : "Mytrips" = I click and go to Calendar

Calendar : I send the 2 datas I need with onPress

  <TouchableOpacity
      style={styles.touchable2}
      onPress={() => this.props.navigation.navigate("MyTrips",
      {selectedStartDate: selectedStartDate, 
       selectedEndDate: selectedEndDate })}
  ></TouchableOpacity>

So now, I go back to MyTrips and I set up the data recovery in the state :

this.state = {
      selectedStartDate: props.navigation.state.params && props.navigation.state.params.selectedStartDate
        ? props.navigation.state.params.selectedStartDate
        : "",
      selectedEndDate: props.navigation.state.params && props.navigation.state.params.selectedEndDate
        ? props.navigation.state.params.selectedEndDate
        : "",

and I want to display it in the screen :

<Text>{this.state.selectedStartDate}{this.state.selectedEndDate}</Text>

But, there is nothing displayed. I think that it's because when I go back to the first screen, the state is not updated with the data I passed. Is anyone that can help me ? I think I'm close to get it work but ... I miss something. Thanks for any help

Upvotes: 0

Views: 52

Answers (1)

Giovanni Esposito
Giovanni Esposito

Reputation: 11176

Ciao, this happens bacause this.state.selectedStartDate and this.state.selectedEndDate will be not updated when Calendar component changes selectedStartDate and selectedEndDate. In this.state = {... you are just copying props into state on first component loading. To update state with new values I suggest you to use componentDidUpdate in MyTrips component. Something like:

componentDidUpdate(prevProps, prevState) {
   // here you could write: 
   // if (prevProps !== this.props) {
   //     this.setState with this.props
   // }
}

Upvotes: 1

Related Questions