Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Refresh previous screen on goBack()

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.

like image 937
Adnan Ali Avatar asked Sep 30 '17 16:09

Adnan Ali


People also ask

How do I refresh my screen in navigation in React Native?

You can easily refresh the screen on focus as given below. React. useEffect(() => { const unsubscribe = navigation. addListener('focus', () => { console.

How do you refresh a page in react?

Use reload() Method to Refresh a Page in React Manually Browsers natively provide a window interface with a location object, including the reload() method.

What is addListener in React Native?

navigation.addListener ​The addListener method takes 2 arguments: type of the event, and a callback to be called on the event. It returns a function that can be called to unsubscribe from the event. The unsubscribe function can be returned as the cleanup function in the effect.


2 Answers

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; }, []); 
like image 76
Mukundhan Avatar answered Sep 22 '22 19:09

Mukundhan


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(() => {     updateSomeFunction()   },[isFocused]); } 
like image 27
Onur Eker Avatar answered Sep 23 '22 19:09

Onur Eker