Rodrigo V
Rodrigo V

Reputation: 514

Run some code when drawer screen gets focused in React-Native

So I have created a drawer navigator:

 <NavigationContainer >
    <Drawer.Navigator  initialRouteName="Home">

      <Drawer.Screen  name="Home" component={HomeScreen} />
      <Drawer.Screen name="Account" component={AccountScreen} />
    </Drawer.Navigator>
  </NavigationContainer>

In the home screen, I want to run some code every time the user goes to that screen:

class HomeScreen extends Component {
     componentWillMount() {
        console.log('WHAT A WONDERFUL WORLD!');
        this.props.setUser();
     }

But it does work with componentWillMount. Is there any way I can detect when the user gets to that particular screen?

Upvotes: 0

Views: 1492

Answers (2)

You can subscribe to the Navigation events inside your componentDidMount function like this:

componentDidMount() {
    this.focusListener = navigation.addListener('focus', () => {
        // do something
    });
}

Remember to unsubscribe inside componentWillUnmount

Upvotes: 1

satya164
satya164

Reputation: 10145

You can use useFocusEffect hook inside your screen:

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

function Profile({ userId }) {
  const [user, setUser] = React.useState(null);

  useFocusEffect(
    React.useCallback(() => {
      const unsubscribe = API.subscribe(userId, user => setUser(user));

      return () => unsubscribe();
    }, [userId])
  );

  return <ProfileContent user={user} />;
}

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

If you can't use hooks, you can listen to focus events but it's less egronomoic https://reactnavigation.org/docs/function-after-focusing-screen/#triggering-an-action-with-a-focus-event-listener

Upvotes: 2

Related Questions