admin管理员组

文章数量:1304270

I'm building an Expo React Native app using Expo Navigation (Stack Navigator) and React Query. When navigating between screens (e.g., from Home to Test screen and back), I need to refetch data when returning to the previous screen. The problem is the component doesn't remount on navigation, hence the query function doesn't trigger/

I'm building an Expo React Native app using Expo Navigation (Stack Navigator) and React Query. When navigating between screens (e.g., from Home to Test screen and back), I need to refetch data when returning to the previous screen. The problem is the component doesn't remount on navigation, hence the query function doesn't trigger/

Share Improve this question asked Feb 4 at 9:45 roborobo 992 silver badges10 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 4

The screen won't be remounted on back navigation as you have mentioned yourself, but it will be refocused. This is described in the official documentation of TanStack query. The provided solution makes use of the useFocusEffect hook of react-navigation.

export function useRefreshOnFocus<T>(refetch: () => Promise<T>) {
  const firstTimeRef = React.useRef(true)

  useFocusEffect(
    React.useCallback(() => {
      if (firstTimeRef.current) {
        firstTimeRef.current = false
        return
      }

      refetch()
    }, [refetch]),
  )
}

In your screens, you need to call the above hook and provide the refetch function returned by useQuery.

本文标签: React Query in Expo wont refetchStack Overflow