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.
You can easily refresh the screen on focus as given below. React. useEffect(() => { const unsubscribe = navigation. addListener('focus', () => { console.
Use reload() Method to Refresh a Page in React Manually Browsers natively provide a window interface with a location object, including the reload() method.
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.
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; }, []);
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]); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With