Update useEffect from the navigation.goBack page?

Asked

Viewed 1,538 times

0

I’m developing a App in ReactNative using Expo, but I can’t update the useEffect(() => {}, []) of the previous route from navigation.goBack().

Example:

Here time the Index page.

function Index(){
  const navigation = useNavigation();
  useEffect({
     ...
  }, []);
  return(
    <View>
      <TouchableOpacity onPress={() => navigation.navigate('Info')}>
        Index
      </TouchableOpacity>
    </View>
  )
}

Here comes the Info page

function Info(){
  const navigation = useNavigation();
  return(
    <View>
      <TouchableOpacity onPress={() => navigation.goBack()}>
        Info
      </TouchableOpacity>
    </View>
  )
}

It happens that the moment you return to Index from the page Info the useEffect page Index does not update.

Is there any way to make these hooks upgrade?

Installed packages:

  • expo: 37.0.3,
  • expo-cli: 3.18.0,
  • @React-navigation/Native: 5.1.5,
  • Ode: v12.13.0,

2 answers

1


The event should be created with useEffect but, the event is the navigation component installed in the project @react-navigation/native: 5.1.5, following the example code contained in documentation:

function Profile({ navigation }) {
  React.useEffect(() => {
    const unsubscribe = navigation.addListener('focus', () => {
      // do something
    });

    return unsubscribe;
  }, [navigation]);

  return <ProfileContent />;
}

You can configure 3 events: focus ( This event is issued when the screen comes into focus), blur ( This event is issued when the screen is blurred) and state ( This event is issued when the browser state changes) and in your case the question is the event focus.

0

The simple way to do this is exactly as was said by the 'Virgilio Novic'. In short, on the screen you want to return, in useEffect you write:

const [load,setLoad] = useState(true)

useEffect(()=>{
   //Chamada de outras funções
   navigation.addListener('focus', ()=>setLoad(!load))
},[load, navigation])

I have a load state to load the functions every time I need it. Each time 'load' changes useEffect is called. In this case, like useEffect navigation.addListener('focus',...) is being called when my screen comes back, I make it change the 'load', causing my 'useEffect' to reload all my functions.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.