React Navigation V.6 - Refetching data in a screen component only when back from other certain screens

54 views Asked by At

I'm using React-Navigation V6 and I have 4 screens. 3 of them are accesible from the first through buttons,

In my first screen I have:

useEffect(() => {
    if (navigation.isFocused()) {
      fetchSomeData();
        }
    }
}, [navigation.isFocused()])

This is because when I get back from two of the screens, I want to refetch the data. However, when I get back from the 3rd screen, I want NOT to refetch the data again.

How do I achieve this? I tried using a dataFetchingFlag variable in React REDUX, but it gets very, very messy, especially if there are more screens.

1

There are 1 answers

0
user18309290 On

Use route parameters. In the first screen call a function only if the certain parameter is set.

useEffect(() => {
  if (route.params?.refresh) {
    fetchSomeData();
  }
}, [route.params?.refresh]);

In other screens set the parameter to true or false to get desired behaviour when navigating back.

navigation.navigate({
  name: 'First',
  params: { refresh: true },
  merge: true,
});

See Passing params to a previous screen for details.

The alternative way is to use onStateChange to listen to state changes and based on that call a function.

<NavigationContainer onStateChange={(state) => console.log(state)}>
  <Stack.Navigator>
...
  </Stack.Navigator>
</NavigationContainer>