Query Doesn't Re-run after navigation

Viewed 486

I have a screen where I am using a query like this:

export const AllFriends: React.FunctionComponent = () => {
  const navigation = useNavigation();

  const { data, error } = useGetMyProfileQuery({
    onCompleted: () => {
      console.log('hellooo')
    },
  });

Every time I visit this page from the home-page, I think the query re-runs as I always see the hellolog. Similarly, from this page, I visit another screen like this:

          <Text
            onPress={() => navigation.navigate('PendingRequests')}>
            Pending Requests (
            {data
              ? data.me.pendingUserRelationsRequestsReceived.totalCount
              : ''}
            )
          </Text>

Every time I visit this screen, I see the hellooo from pending again. This screen looks like this:

export const ReceivedPendingRequests: React.FunctionComponent = () => {
  const navigation = useNavigation();

  const { data, error } = useGetMyProfileQuery({
    onCompleted: () => {
      console.log('hellooo from pending')
    },
  });

  return (
    <SafeAreaView style={styles.safeView}>
      <Container style={styles.container}>
        <Text
          style={styles.backText}
          onPress={() => navigation.navigate('AllFriends')}>
          Zurück
        </Text>
      </Container>
    </SafeAreaView>
  );
};

Now the problem is that when I navigate back to AllFriends, the query should re-run and I should see the hello log again just like I see when I come from the Homepage to AllFriends. But I don't.

However, if I come back from AllFriends to PendingRequests, I see the log hellooo from pending again.

Edit:

  useFocusEffect(()=>{
    getMyProfile()
  },[]);
  
  const getMyProfile = () => {
    const { data, error } = useGetMyProfileQuery({
      onCompleted: () => {
        console.log('hellooo')
      },
      //fetchPolicy: 'network-only',
    });
  }
2 Answers

You have to call refetch it will re-run the query for you. You can pass it to other screens aswell.

You can get it like this:

const {loading, data, refetch} = useQuery(Query, {})

Now in you useFocuseEffect just call this:

 useFocusEffect(()=>{
   React.useCallback(() => {
    refetch();
    }, [])
 },[]);

when using navigation.navigate the screen doesn't "unmount", so it will not be reinitialized as fresh from the start as the screen does when you're using navigation.replace

Try using navigation.replace instead of navigation.navigate. I hope it helps, if not, let me know.

Related