Home > Blockchain >  useEffect not working in Stack Navigation
useEffect not working in Stack Navigation

Time:10-06

I have 2 screens in Stack Navigator.

All Categories, Add a new category

In the All Categories screen, all categories are displayed.

useEffect(() => {
    loadCategories();
  }, []);

This is the useEffect hook that load all the categories.

I have made a touchable opacity to navigate to Add a new category screen, So users can easily add a new category if needed.

What I'm expecting to do: So after adding a new category and going back to the All Categories screen loadCategories() should run again, So the user can see the newly added category there. But the problem is when I add a new category and go back the loadCategories() function doesn't execute again. What will be the cause for this?

CodePudding user response:

If you want to load categories when screen is focus

function Categories({ navigation }) {
  React.useEffect(() => {
    const loadCategories = navigation.addListener('focus', () => {
     loadCategories();
    });

    return loadCategories;
  }, [navigation]);

  ...rest
}

CodePudding user response:

Often we need to fetch data when we come to some screens back,

For this, there is a hook from the @react-navigation/native library (useFocusEffect), which we can use to accomplish such requirements.

For Ex.

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} />;
}

In the above code, Whenever the ProfileContent screen is getting focused, the code inside the useFocusEffect will re-run.

Refer to official docs for in-depth understanding.

CodePudding user response:

I found this answer which is relatable to this question. https://stackoverflow.com/a/62703838/19317939

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

useEffect(() => {
    if (isFocused) loadCategories();
  }, [isFocused]);
  • Related