Last active
April 7, 2025 10:15
-
-
Save OkancanCosar/9ff553dacc9221bb1e0a64485ea45307 to your computer and use it in GitHub Desktop.
useQuery cancel signal
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import React, { useEffect, useRef } from 'react' | |
| import { View } from 'react-native' | |
| import { useQuery, useQueryClient } from '@tanstack/react-query' | |
| import { useIsFocused } from '@react-navigation/native' | |
| export const MyScreen = () => { | |
| const isFocused = useIsFocused(); | |
| const queryClient = useQueryClient(); | |
| const controllerRef = useRef<AbortController | null>(null); | |
| const { data, isFetching, isRefetching } = useQuery({ | |
| queryKey: ['list'], | |
| queryFn: async () => { | |
| const abortController = new AbortController(); | |
| controllerRef.current = abortController; | |
| return myApi.getList(abortController.signal); | |
| }, | |
| refetchInterval: 10000, // 10 seconds, | |
| enabled: isFocused, // for tabbar navigation | |
| }); | |
| useEffect(() => { | |
| if (!isFocused) { | |
| controllerRef.current?.abort(); | |
| queryClient.cancelQueries(['list']); | |
| } | |
| }, [isFocused]); | |
| const showSkeletons = isFetching && !isRefetching | |
| return ( | |
| <View style={{}}> | |
| <></> | |
| </View> | |
| ) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment