Refresh previous screen on goBack()

React NativeReact RouterReact Native-AndroidReact Native-IosReact Native-Navigation

React Native Problem Overview


I am new to React Native. How can we refresh/reload previous screen when returning to it by calling goBack()?

Lets say we have 3 screens A, B, C:

A -> B -> C

When we run goBack() from screen C it goes back to screen B but with old state/data. How can we refresh it? The constructor doesn't get called 2nd time.

React Native Solutions


Solution 1 - React Native

Adding an Api Call in a focus callBack in the screen you're returning to solves the issue.

componentDidMount() {
    this.props.fetchData();
    this.willFocusSubscription = this.props.navigation.addListener(
      'willFocus',
      () => {
        this.props.fetchData();
      }
    );
  }

  componentWillUnmount() {
    this.willFocusSubscription.remove();
  }

UPDATE 2021:

  componentDidMount() {
    this.props.fetchData();
    this.willFocusSubscription = this.props.navigation.addListener(
      'willFocus',
      () => {
        this.props.fetchData();
      }
    );
  }

  componentWillUnmount() {
    this.willFocusSubscription();
  }

If you use React Hook:

  React.useEffect(() => {
      fetchData();
      const willFocusSubscription = props.navigation.addListener('focus', () => {
        fetchData();
    });

    return willFocusSubscription;
}, []);

Solution 2 - React Native

How about using useIsFocused hook?

https://reactnavigation.org/docs/function-after-focusing-screen/#re-rendering-screen-with-the-useisfocused-hook

const componentB = (props) => { 
  // check if screen is focused
  const isFocused = useIsFocused();

  // listen for isFocused, if useFocused changes 
  // call the function that you use to mount the component.

  useEffect(() => {
    isFocused && updateSomeFunction()
  },[isFocused]);
}

Solution 3 - React Native

For react-navigation 5.x use > 5.x

use

componentDidMount() {
  this.loadData();

  this.focusListener = this.props.navigation.addListener('focus', () => {
    this.loadData();
    //Put your Data loading function here instead of my this.loadData()
  });
}

For functional component

function Home({ navigation }) {
  React.useEffect(() => {
    const unsubscribe = navigation.addListener('focus', () => {
      loadData();
      //Put your Data loading function here instead of my loadData()
    });

    return unsubscribe;
  }, [navigation]);

  return <HomeContent />;
}

Solution 4 - React Native

On your screen B constructor will work like magic :)

    this.props.navigation.addListener(
          'didFocus',
          payload => {
            this.setState({is_updated:true});
          }
    );

Solution 5 - React Native

Yes, constructor is called only for the first time and you can't call it twice.

First: But you can separate the data getter/setter from the constructor and put it in a function, this way you can pass the function down to the next Scene and whenever you're going back you may simply recall the function.

Better: You can make a go back function in your first scene which also updates the scene while going back and pass the go back function down. This way the second scene would not be aware of your update function which is reasonable.

Best: You can use redux and dispatch a go-back action in your second scene. Then in your reducer you take care of going back & refreshing your scene.

Solution 6 - React Native

The built in listener function which comes with React-Navigation would be the easiest solution. Whenever a component is 'focused' on a again by navigating back, the listener will fire off. By writing a loadData function that can be called both when loading the Component AND when the listener is notified, you can easily reload data when navigating back.

   componentWillMount(){
    this._subscribe = this.props.navigation.addListener('didFocus', () => {
     this.LoadData();
     //Put your Data loading function here instead of my this.LoadData()
    });}

Solution 7 - React Native

I have a similar situation and the way i refreshed was to reset the route when the back button is pressed. So, what happens is when the back button is pressed the screen is re-pushed into the stack and the useEffect on my screen loads the data

navigation.reset({
  index: 0,
  routes: [{ name: "SCREEN WHERE THE GOBACK BUTTON SHOULD GO" }],
});

Solution 8 - React Native

Update for react-navigation v5 and use the React Hooks. Actually, the use is the same with react base class. For more detail, please checkout the documentation here

Here is the sample code:

function Profile({ navigation }) {
  React.useEffect(() => {
    const unsubscribe = navigation.addListener('focus', () => {
      // do something
    });

    return unsubscribe;
  }, [navigation]);

  return <ProfileContent />;
}

As above code, We add the event listener while the variable navigation change then We do something like call function refresh() and finally, we return the function for removing the event listener. Simple!

Solution 9 - React Native

I think we have a very easy way (which works in 2021) to do so. Instead of using goBack or navigate, you should use push

this.props.navigation.push('your_route_B'). 

You can also pass params in the same way as we pass in navigate.

The only difference b/w navigate and push is that navigate checks if the route which we are passing exists in the stack. Thus taking us to the older one but, push just sends us there without checking whether that is in the stack or not (i.e, whether the route was visited earlier or not.)

Solution 10 - React Native

Easy! insert the function inside useFocusEffect(func)

import { useFocusEffect } from '@react-navigation/native' 

Solution 11 - React Native

For react navigation (5.x), you just need to add a focus subscription and put your component initializing logic in a separate function like so:

componentDidMount() {

    this.init();

    this.didFocusSubscription = this.props.navigation.addListener(
      'focus',
      () => {
        this.init();
      }
    );


  }


init = async () => {
   //fetch some data and set state here
   
  }

Solution 12 - React Native

This can be achived by useFocusEffect from '@react-navigation/native'

useFocusEffect will effect every time when screen is focus

Ref: https://reactnavigation.org/docs/use-focus-effect/

import { useFocusEffect } from '@react-navigation/native';

function Profile({ }) {
  
  useFocusEffect(
    React.useCallback(() => {
      //Below alert will fire every time when profile screen is focused
        alert('Hi from profile')
    }, [])
  );

  return // ...code ;
}

Solution 13 - React Native

If you're trying to get new data into a previous view, and it isn't working, you may want to revisit the way you're piping data into that view to begin with. Calling goBack shouldn't effect the mounting of a previous component, and likely won't call its constructor again as you've noted.

As a first step, I would ask if you're using a Component, PureComponent, or Functional Component. Based on your constructor comment it sounds like you're extending a Component class.

If you're using a component, the render method is subject to shouldComponentUpdate and the value of your state is in your control.

I would recommend using componentWillReceiveProps to validate the component is receiving the new data, and ensuring its state has been updated to reflect the new data.

If you're using the constructor to call an API or async function of some kind, consider moving that function into a parent component of both the route you're calling goBack from and the component you're wanting to update with the most recent data. Then you can ask your parent component to re-query the API, or update its state from a child component.

If Route C updates the "state/data" of the application, that update should be propagated to a shared parent of routes A, B and C, and then passsed down as a prop.

Alternatively, you can use a state management solution like Redux to maintain that state independent of parent/child components - you would wrap your components in a connect higher-order component to get the latest updates any time the application state changes.

TL;DR Ultimately it sounds like the answer to your question is rooted in where your application state is being stored. It should be stored high enough in your component hierarchy that each route always receives the latest data as a prop, passed from its parent.

Solution 14 - React Native

This answer assumes that the react-native-navigation library is being used, which is unlikely because it doesn't actually have a goBack() method...

The constructor doesn't call a second time because screen A and B are still rendered (but hidden behind screen C). If you need to know when screen B is going to be visible again you can listen to navigation events.

class ScreenB extends Component {
  constructor(props) {
    super(props);
    // Listen to all events for screen B
    this.props.navigator.setOnNavigatorEvent(this.onNavigatorEvent);
  }

  onNavigatorEvent = event => {
    switch (event.id) {
      case 'willAppear':
        // refresh your state...
        break;
  };
}

Other events: willDisappear, didAppear, didDisappear

An alternate solution to your problem is to use a state management solution like Redux to provide the state to all screens whenever it is updated (rather than just on screen transitions. See old react-native-nav/redux example.

Solution 15 - React Native

Thanks to @Bat. I have spent a lot of hours on finding the answer and finally, I got a basic solution which is working according to my needs. I was quite worried though. Simply make a function like this in your previous activity make sure to bind it.

    changeData(){
    var mydata= salesmanActions.retrieveAllSalesman();
    this.setState({dataListFill: mydata});
    alert('' + mydata.length);
    }

Simple, then in constructor bind this,

    this.changeData= this.changeData.bind(this);

After that, as I am using react native navigation, so I will simply pass this function to the second screen just like the code below:

    onPress={() => this.props.navigation.navigate('Add Salesman', {doChange: 
    this.changeData} )}
        

So when the new screen registered as "Add Salesman" will be called, a parameter named "doChange" which is assigned a function will also be transfered to other screen. Now, in other screen call this method anywhere, by :

    this.props.route.params.doChange();

It works for me. I hope works for you too, THANKS for the idea @Bat.

Solution 16 - React Native

 let we have 2 screen A and B , screen A showing all data . and screen B is responsible for adding that data. we add some data on using screen B and want to show instant changes on Screen A . we use below code in A   

    componentDidMount(){
                this.focusListener = this.props.navigation.addListener('focus', () => {
                thi`enter code here`s.startData();
                //Put your Data loading function here
            }); 
    }

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAdnan AliView Question on Stackoverflow
Solution 1 - React NativeMukundhanView Answer on Stackoverflow
Solution 2 - React NativeOnur EkerView Answer on Stackoverflow
Solution 3 - React NativekvadityaazView Answer on Stackoverflow
Solution 4 - React NativeBrijesh SinghView Answer on Stackoverflow
Solution 5 - React NativeBatView Answer on Stackoverflow
Solution 6 - React NativeRawBDataView Answer on Stackoverflow
Solution 7 - React NativeehtulhaqView Answer on Stackoverflow
Solution 8 - React NativenahoangView Answer on Stackoverflow
Solution 9 - React NativeIrfan waniView Answer on Stackoverflow
Solution 10 - React NativeTurjoy SahaView Answer on Stackoverflow
Solution 11 - React NativeAcheme PaulView Answer on Stackoverflow
Solution 12 - React NativeHardik DesaiView Answer on Stackoverflow
Solution 13 - React Nativejoel.softwareView Answer on Stackoverflow
Solution 14 - React NativeRoyce TownsendView Answer on Stackoverflow
Solution 15 - React NativeMehdi RazaView Answer on Stackoverflow
Solution 16 - React Nativezaheer ahamdView Answer on Stackoverflow