react-apollo icon indicating copy to clipboard operation
react-apollo copied to clipboard

useQuery Hook always return true on loading state

Open Dalejan opened this issue 7 years ago • 41 comments

Hi, im having this issue on every useQuery hook implementation: the data is actually fetched from the backend (i can see it in the network devops from google), but the loading state of the query is always true, this causes an infinite loop that doesn't let me show any data, only loading template.

Intended outcome:

Data response from useQuery hook same as preview or response from network devops loading = true, then false error = undefined

Actual outcome:

data = {} loading = always true error = undefined

image

How to reproduce the issue: Imports:

import { gql, ApolloClient, HttpLink, InMemoryCache } from "apollo-boost";
import { useQuery } from "@apollo/react-hooks";

Query:

const GET_EVENT = gql`
  query getEvent($id: ID!) {
    event(id: $id) {
      _id
    }
  }
`;

Function:

function App() {
  const { loading, error, data } = useQuery(GET_EVENT, {
    variables: { id: "5d5184d3ecbfcaa34ef96182" },
    client: new ApolloClient({
      link: new HttpLink({ uri: URI }),
      cache: new InMemoryCache()
    })
  });

  if (loading) return "Loading...";
  if (error) return `Error! ${error.message}`;

  return <div>Ok</div>;
}

export default App;

Version NOTE: I have already tried with react-apollo instead of apollo-boost, same result

System: OS: Linux 4.15 Ubuntu 18.04.2 LTS (Bionic Beaver) Binaries: Node: 8.10.0 - /usr/bin/node npm: 6.8.0 - /usr/local/bin/npm Browsers: Chrome: 75.0.3770.142 Firefox: 68.0.1 npmPackages: apollo-boost: ^0.4.4 => 0.4.4 react-apollo: ^3.0.0 => 3.0.0

Dalejan avatar Aug 13 '19 17:08 Dalejan

Having the same issue

zestian56 avatar Aug 13 '19 18:08 zestian56

I'm having the exact same issue.

mateo2708 avatar Aug 13 '19 18:08 mateo2708

I'm running into something similar, although I've only observed it in a mocked Cypess test environment where fetch is mocked and resolved immediately with the query data. It is working in almost all of our tests (and was working always consistently prior to updating to the latest react-apollo version), but we now have a few tests with a query that will get caught in a loading state about 50% of the time (sometimes more or less than 50% depending on the test). It seems to be some kind of race condition because if we artificially add a delay of 500 ms, the tests always passes again.

Tried to dig in a little bit to see where things might be going wrong, but haven't hit any conclusions yet. startQuerySubscription is definitely called for this query, but the next callback is never triggered.

Edit: Have found a little bit more detail for my problem. I added a log right here: https://github.com/apollographql/react-apollo/blob/master/packages/hooks/src/data/QueryData.ts#L405 in handleErrorOrCompleted.

console.log("IN HANDLE_ERROR_OR_COMPLETED", "loading: ", loading, "data: ", data)

For the case that gets stuck in loading: IN HANDLE_ERROR_OR_COMPLETED loading: false data: {siteCertificate: {…}}

The case that doesn't get stuck in loading: IN HANDLE_ERROR_OR_COMPLETED loading: true data: undefined IN HANDLE_ERROR_OR_COMPLETED loading: false data: {siteCertificate: {…}}

So it seems like the problem for me has to do with the query resolving too early, which results in it getting stuck. I'm guessing something with the Observable isn't setup in time when the query resolves so quickly. This would make sense given that an artificial delay helps resolve whatever race is going on.

TLadd avatar Aug 16 '19 12:08 TLadd

Having the same issue as well.

mtsamis2 avatar Aug 20 '19 13:08 mtsamis2

@Dalejan did you try with "no-cache" option for fetch-policy ? I have a similar issue, but it "works" if I disable the cache ("cache-and-network", "network-only", etc don't work).

eltonio450 avatar Aug 30 '19 09:08 eltonio450

Same. And no-cache "works" indeed.

mpgon avatar Sep 04 '19 13:09 mpgon

ok, we fixed our problem, so our solution, which may not be relavant in this case:

We use fragments on unions and interface (https://www.apollographql.com/docs/react/advanced/fragments/#fragments-on-unions-and-interfaces)

For some reason, it was working with react-apollo 2.4.1 without the IntrospectionFragmentMatcher . But not anymore in 2.5.3 and above, and it showed the behavior described in the @Dalejan initial post: re-fetching indefinitely. Setting up the IntrospectionFragmentMatcher fixed it :)

Hope it helps some of you :)

eltonio450 avatar Sep 04 '19 16:09 eltonio450

In my case, since this is not happening more often than it is, this seems to mitigate it:

const useFixLoading = () => {
  const refetchRef = useRef(() => {});
  const timeoutRef = useRef(null);
  const [isLoading, setIsLoading] = useState(false);

  useEffect(() => {
    if (timeoutRef.current != null) {
      clearTimeout(timeoutRef.current);
      timeoutRef.current = null;
    }
    if (isLoading) {
      timeoutRef.current = setTimeout(() => {
        refetchRef.current();
      }, 3000);
    }
  }, [isLoading]);

  return (loading, refetch) => {
    setIsLoading(loading);
    refetchRef.current = refetch;
  };
};

const MyQuery = (...) => {
  const fixLoading = useFixLoading();

  return (
    <Query
      query={query}
      variables={variables}
      fetchPolicy="network-only"
    >
      {({ loading, error, data, refetch }) => {
        fixLoading(loading, refetch);
        // ..
      }}
    </Query>
  );
};

mpgon avatar Sep 04 '19 16:09 mpgon

Could someone test this out with React Apollo 3.1.0 and let us know if this is still an issue? thanks!

hwillson avatar Sep 06 '19 12:09 hwillson

I am also experiencing this issue. I tried to follow @TLadd's approach and artificially add a delay of 500 ms, but the results are inconsistent.

"apollo-client": "^2.6.4",
"cypress": "3.4.1",
"react-apollo": "^3.0.1"

jeffal avatar Sep 06 '19 21:09 jeffal

Ran into this same issue today (loading remained true in inconsistent cases after data returned from the DB), and I can confirm that { fetchPolicy: "no-cache" } "worked" for me as well. Thanks, @eltonio450!

    "@apollo/react-hooks": "^3.0.0",
    "react-apollo": "^3.0.0",

This did the trick for me (although you will lose the benefits of cache).

const { loading, error, data } = useQuery(
    QUERY,
    { fetchPolicy: "no-cache" }
  );

mddilley avatar Sep 07 '19 00:09 mddilley

@hwillson I tried updating to 3.1.0 but I got this problem: https://github.com/apollographql/react-apollo/issues/3482

mpgon avatar Sep 10 '19 15:09 mpgon

Is anyone still seeing this issue with React Apollo 3.1.0?

hwillson avatar Sep 14 '19 17:09 hwillson

Not so far :)

mpgon avatar Sep 16 '19 08:09 mpgon

Thanks @mpgon - I'll mark this as resolved, but if anyone is still encountering this let me know.

hwillson avatar Sep 16 '19 09:09 hwillson

@hwillson Encountered this again. I don't know if anything that was done would impact the frequency of when this occurs, because it appears to be happening less since I upgraded to 3.1.0, but definitely still happening.

mpgon avatar Sep 25 '19 13:09 mpgon

@hwillson Just saw this in our app again with 3.1.2, happening in a specific component and only on the first load. But in that situation it is consistent. I'm not able to create a small repro so not sure how to best help :/

Like the above commenters mentioned earlier this can be 'fixed' by disabling the cache.

emilsjolander avatar Oct 10 '19 15:10 emilsjolander

@hwillson I'm seeing this issue, too, using the latest version of hooks...

@Dalejan please consider reopening this issue

    "@apollo/react-hooks": "^3.1.3",
    "@apollo/react-ssr": "^3.1.3",
    "apollo-cache-persist": "^0.1.1",
    "apollo-client": "^2.6.4",
    "apollo-link": "^1.2.13",
    "apollo-link-error": "^1.1.12",
    "apollo-link-http": "^1.5.16",

My query is a local query and therefore the 'no-cache' solution is absolutely not an option, not that it is really a solution anyways

Edit: Initially, I was using ssr: false because my query is accessing the localStorage cache. However, by setting: ssr: true, the problem was resolved. I believe that I ~ should ~ still be using ssr: false on this query, but it's working so that'll just be my little secret

ajhool avatar Oct 28 '19 23:10 ajhool

I can confirm this is still occurring in 3.1.3.

dvester avatar Oct 31 '19 15:10 dvester

We are seeing this on 3.1.3. Trying to migrate over from https://github.com/trojanowski/react-apollo-hooks, but this is stopping us 😞

davetapley avatar Nov 07 '19 23:11 davetapley