question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

useQuery continuously fetches; loading always true

See original GitHub issue

Intended outcome: Fetch once. Loading should be true, then false. Data should not be undefined.

Actual outcome: Fetches nonstop (looped)

Loading always true. Data always undefined. Error always undefined.

Server + Playground works as intended. No errors are displayed in RN Debugger, even though I’ve turned all error logging on.

How to reproduce the issue:

//Schema
const typeDefs = gql`
  type Query {
    recordsByTime(): [Record]
  }
  type Record {
    id: Int
  }
`

const RecordsByTime = gql`
    query RecordsByTime() {
        recordsByTime() {
            id
        }
    }
`
 const { loading, error, data,  } = useQuery(RecordsByTime, {
        client,
        variables: {},
        errorPolicy: 'all',
        fetchPolicy: 'no-cache',
        onCompleted: (c) => {
            console.log(c) //Never gets called
        },
    })

export const resolvers = {
      recordsByTime: async (root, { }, context) => {
          return [{ id: 1}, { id: 2}, { id: 3 }];
      }
}

export const getApolloClient = (token = null) => {
    let httpURI = 'http://DOMAIN.com:4000/graphql'
    if (__DEV__) {
        httpURI = Platform.OS == 'ios' ? 'http://localhost:4000/graphql' : 'http://10.0.2.2:4000/graphql'
    }
    const httpLink = createHttpLink({
        uri: httpURI,
    })
    const authLink = setContext(async (_, { headers }) => {
        return {
            headers: {
                ...headers,
                authorization: token ? `Bearer ${token}` : '',
            },
        }
    })
    const errorLink = onError(({ graphQLErrors, networkError }) => {
        if (graphQLErrors)
            graphQLErrors.map(({ message, locations, path }) =>
                console.log(`[GraphQL error]: Message: ${message}, Location: ${locations}, Path: ${path}`)
            )
        if (networkError) console.log(`[Network error]: ${networkError}`)
    })
    const client = new ApolloClient({
        link: from([authLink, errorLink, httpLink]),
        cache: new InMemoryCache(),
    })
    return client
}

Versions System: OS: macOS 11.4 Binaries: Node: 16.2.0 - /usr/local/bin/node Yarn: 1.22.10 - /usr/local/bin/yarn npm: 7.13.0 - /usr/local/bin/npm Browsers: Chrome: 91.0.4472.77 Safari: 14.1.1 npmPackages: @apollo/client: ^3.3.19 => 3.3.19 apollo-cache-inmemory: ^1.6.6 => 1.6.6 apollo-client: ^2.6.10 => 2.6.10 apollo-link: ^1.2.14 => 1.2.14 apollo-link-context: ^1.0.20 => 1.0.20 apollo-link-error: ^1.1.13 => 1.1.13 apollo-link-http: ^1.5.17 => 1.5.17 react-apollo: ^3.1.5 => 3.1.5

Issue Analytics

  • State:open
  • Created 2 years ago
  • Reactions:4
  • Comments:5 (1 by maintainers)

github_iconTop GitHub Comments

3reactions
felixchancommented, Jun 14, 2021

Fixed in my case ; it was a timestamp (Date) in the variables.

const time = useRef(DateTime.local().toString())

1reaction
dylanwulfcommented, Jun 13, 2021

@JacksonMalloy Here is an ApolloLink that I wrote to add timeout functionality:

import { ApolloLink, Observable } from '@apollo/client';
import type { OperationDefinitionNode } from 'graphql';
import { Kind } from 'graphql/language';

const timeoutLink = new ApolloLink((operation, forward) => {
	const { operation: operationType } = operation.query.definitions.find(
		definition => definition.kind === Kind.OPERATION_DEFINITION,
	) as OperationDefinitionNode;

	if (operationType === 'subscription') {
		// timeout should not apply to subscriptions
		return forward(operation);
	}

	// timeout value can be specified through the `context` object in useQuery/useMutation
	// value is in milliseconds and defaults to 30,000ms
	const { timeout = 30000 } = operation.getContext();

	return new Observable(subscriber => {
		let timeoutId: number;

		const forwardSubscription = forward(operation).subscribe({
			next: data => {
				subscriber.next(data);
			},
			complete: () => {
				window.clearTimeout(timeoutId);
				subscriber.complete();
			},
			error: err => {
				window.clearTimeout(timeoutId);
				subscriber.error(err);
			},
		});

		timeoutId = window.setTimeout(() => {
			forwardSubscription.unsubscribe();
			subscriber.error(new Error('Timeout'));
		}, timeout);

		return () => {
			window.clearTimeout(timeoutId);
			forwardSubscription.unsubscribe();
		};
	});
});

export default timeoutLink;

Read more comments on GitHub >

github_iconTop Results From Across the Web

useQuery Hook always return true on loading state #3361
Hi, im having this issue on every useQuery hook implementation: the data is actually fetched from the backend (i can see it in...
Read more >
The useQuery hook | Lift-off I: Basics | Apollo Odyssey
The useQuery hook is the primary API for executing queries in a React application. ... As long as loading is true (indicating the...
Read more >
useQuery | TanStack Query Docs
fetching : Is true whenever the queryFn is executing, which includes initial loading as well as background refetches. · paused : The query...
Read more >
Apollo Client useQuery always return loading as true
I have a react component that uses apollo client and uses useQuery to get information from the API. The problem I ...
Read more >
Fetch, Cache, and Update Data Effortlessly with React Query
The easiest way to fetch a query is the useQuery hook: ... loading: The query has no data and it is currently fetching...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found