Home > database >  How can I execute the same function on each screen with navigation? on react native
How can I execute the same function on each screen with navigation? on react native

Time:08-16

How can I execute the same function on each screen with navigation? I'm using react native and typescript I have the navigation file where home, profile, etc...

//I have my function like this and I want this function to be executed when you navigate to profile, home, etc


   const getFunction = (): void => {
console.log('execute function')
...
   }

// I don't know if this part is right because at the moment it doesn't work and I don't know how it could be
   useEffect(() => {
     const listener =
       navigation.addListener('focus', (e) => {
         getFunction()
       })
     return() => listener
   }, [navigation])

...

return (
         <Stack.Screen
           name='home'
           component={home}
         />
         <Stack.Screen
           name='profile'
           component={profile}
         />
...
)

Please if you could help me i would really appreciate it!! :)

CodePudding user response:

You can use screenListeners prop on the navigator. This way you can specify listeners for events from all screens. As example like so:

<Stack.Navigator
  screenListeners={{
    state: (e) => {
      getFunction();
    },
  }}
>
  <Stack.Screen name="home" component={home} />
  <Stack.Screen name="profile" component={profile} />
</Stack.Navigator>
  • Related