Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

react-native re-run function on navigating back

I'm using react-navigation to navigate between screens, now in my "cases.js" I have a fetch method that gets the cases from the API when the user click on one it loads another page with the clicked case to either accept or deny the case itself.

Either way the user will be redirected to the "cases.js" page if the user accepts the case I no longer need the case to be available on the "cases.js" page list.

Here is my cases.js file

export default class PendingCases extends Component {

  constructor(props) {

    super(props);

    this.state = { cases : [], user : '', refreshing : false }

  }

  componentDidMount = async () => {

    await this._getUser();

    await this._getCases();

  }

  _getUser = async () => {

    let user = await AsyncStorage.getItem('user');

    await this.setState({ user : JSON.parse(user) })

  }

  _getCases = async () => {

    try {

      await this.setState({ refreshing : true })

      let pendingCases = await fetch('http://192.168.1.101:1337/user/cases?status=pending&userType=patient&id=' + this.state.user.id);

      let response = await pendingCases.json();

      await this.setState({ cases : response.cases });

      await this.setState({ refreshing : false })

    } catch (err) {

      console.log(err);

    }

  }

  render() {

    let casesArray = this.state.cases.map((singleCase, index) => {
      return (
        <View key={ index }>
          <TouchableOpacity onPress={ () => this.props.navigation.navigate('SelectedCaseDetails') } style={ styles.caseButton }>
            <View>
              <View style={{ marginBottom: 10, marginTop: 5 }}>
                <LinearTextGradient locations={[0, 1]} start={{x: 0, y: 0}} end={{x: 1, y: 0}} colors={['#a4d294', '#3ac6f3']} style={{ fontWeight: 'bold' }}>
                  {singleCase.doctor.name}
                </LinearTextGradient>
                <Text style={{ position: 'absolute', right: 0, fontWeight: '600', color: 'black'}}> 00231 </Text>
              </View>
              <View style={{ marginBottom: 10 }}>
                <Text> {singleCase.additionalInformation} </Text>
              </View>
              <View style={{ marginBottom: 10, flex : 1, flexDirection: 'row'}}>
              <Image style={ styles.statusImage } source={require('../images/status.png')} />
                <Text style={{ marginRight : 30, color : 'rgba(0, 0, 0, .8)', flex : 8}}>
                 Status <Text style={{ color : 'rgb(240, 151, 166)', marginLeft : 60 }}> {singleCase.status} </Text> </Text>
                <Text style={{ position: 'absolute', right: 0, fontWeight: '300', color: 'grey'}}> { parsedDate } </Text>
              </View>
            </View>
          </TouchableOpacity>

        </View>
      )
    });

    return (
      <View>
        { casesArray }
      </View>
    )

  }

}

How can I re-run the this._getCases() function when I redirect the user from the one-level deep page ?

I'm redirecting the user the same way as navigating to any other screen this.props.navigation.navigate('CasesScreen')

like image 644
Abdul-Elah JS Avatar asked Oct 26 '25 20:10

Abdul-Elah JS


1 Answers

If your component is already mounted, you can use react-navigation's listeners to check whether the component is focused or not.

You'll need

didFocus: the screen focused (if there was a transition, the transition completed)

componentDidMount () {
    this._getUser();
    this._onFocusListener = this.props.navigation.addListener('didFocus', (payload) => {
      this._getCases();
    });
}

and remove it once the component gets unmounted.

componentWillUnmount () {
      this._onFocusListener.remove()
}
like image 200
Pritish Vaidya Avatar answered Oct 28 '25 09:10

Pritish Vaidya



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!