Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React-Navigation: Call function whenever page is navigated to

Tags:

I am developing a React-Native app using React-Navigation, and I am using a stack navigator.

How can I call a function whenever a page is navigated to, including on goBack() events? If I place the method in my constructor, it is only triggered on its initial creation, and not when it is attained through goBack().

like image 301
Adam Arcaro Avatar asked Jul 15 '18 17:07

Adam Arcaro


People also ask

How do you call a function automatically in react?

In React, the onClick handler allows you to call a function and perform an action when an element is clicked. onClick is the cornerstone of any React app. Click on any of the examples below to see code snippets and common uses: Call a Function After Clicking a Button.

How do you call a function when screen focus React Native?

There are two approaches to calling an action on screen focusing: Using the withNavigationFocus higher order component provided by react-navigation. Listening to the 'didFocus' event with an event listener.

How do you send data while navigating in react?

To pass data when navigating programmatically with React Router, we can call navigate with an object. Then we can use the useLocation hook to return the object's data. const navigate = useNavigate(); navigate('/other-page', { state: { id: 7, color: 'green' } });


1 Answers

use Navigation Events I believe you can use did focus and will blur

<NavigationEvents
      onWillFocus={payload => console.log('will focus', payload)}
      onDidFocus={payload => console.log('did focus', payload)}
      onWillBlur={payload => console.log('will blur', payload)}
      onDidBlur={payload => console.log('did blur', payload)}
    />

https://reactnavigation.org/docs/en/navigation-events.html

EDIT 2022

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

const isFocused = useIsFocused();

React.useEffect(()=>{
 if(isFocused){

   // callback
 }
},[isFocused])
like image 181
Alireza tk Avatar answered Oct 05 '22 06:10

Alireza tk