Fanto
Fanto

Reputation: 137

React - native StackNavigator refresh previous component after hitting back button

I'm stuck for weeks on this problem that I can't solve. I have been through a lot of different solution and none of them is working..

Let-s say I have component A and component B

Component A : contains a flatlist, when click on one item leads me to component B.

Component B: contains details of component A items, when clicking on a button update data, data that component A is using in state current, which make the clicked items turn to orange. I would like when hitting back button to update those data in component A and actually have the clicked items in orange, right now nothing is happening..

Component A :

async interventionList(){
    const planningList = await getInterventionList(this.state.userToken, '2019-02-27', '2019-02-27'); 
    this.setState({list: planningList});
 }

renderItem = ({ item }) => (
    <View>
      <TouchableHighlight onPress={
        () =>  this.props.navigation.navigate('InterventionStart', { getIntervention: () => this.interventionsList() })}>
        <View style={[styles.block, this.state.current !== null && this.state.current.remoteInterventionId === item.num ? styles.began : styles.notbegan]}>
          <Text> {SomeData} <Text>
          </View>
        </View>
      </TouchableHighlight>
    </View>
  )

Component B :

componentWillUnmount() {
    this.props.navigation.state.params.getIntervention();
  }

But nothing happens. I tried to console log, to see if those functions where called after clickin on back button and they are... So I don't understand what I am doing wrong or is it not the way to do this at all ?

Upvotes: 1

Views: 519

Answers (1)

Sarmad Shah
Sarmad Shah

Reputation: 3805

You can use willFocus method of react-navigation

in your componentDidMount or in your constructor

this.willFocus = this.props.navigation.addListener('willFocus', () => {
      this.interventionList();
    });

It will call your interventionList method whenever your component is about to be focused. Make sure you remove the listener on your componentWillUnmount

this.willFocus.remove();

For reference https://reactnavigation.org/docs/en/navigation-events.html

Upvotes: 2

Related Questions