React Native - React Navigation rerender panel on goBack()

GIV picture GIV · Mar 23, 2018 · Viewed 9.3k times · Source

I am using React Navigation in my app. How can I refresh the data on my previous panel when going back to it?

A practical example would be: I am currently in Panel A, I navigate to Panel B where I update data in my database which is displayed in Panel A. After I goBack() to Panel A after changing the data in the database I wish Panel A has now rerendered and holds the new data from the database.

I have read that I can pass a custom refresh function as params to the child class and call it before navigating back, however I think this is not a neat way to achieve what I want since I update a component which is not yet mounted and I can just throw an error.

Answer

Jitender Badoni picture Jitender Badoni · Apr 20, 2018

This is how i achieved!

In Panel A

refreshFunction()
{
    //your refresh code should be here
}

 <TouchableOpacity onPress={()=>{
   this.props.navigation.navigate('PanelB', {refreshFunction: this.refreshFunction});
 }}>
    Redirect to Panel B
 </TouchableOpacity>

In Panel B

const refreshFunction = this.props.navigation.state.params.refreshFunction;
if(typeof refreshFunction === 'function')
{
  refreshFunction();                
  //your back function
  this.goBack();
}