Skip to content
This repository has been archived by the owner on Apr 13, 2023. It is now read-only.

useQuery Hook always return true on loading state #3361

Closed
Dalejan opened this issue Aug 13, 2019 · 41 comments
Closed

useQuery Hook always return true on loading state #3361

Dalejan opened this issue Aug 13, 2019 · 41 comments

Comments

@Dalejan
Copy link

Dalejan commented Aug 13, 2019

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

@zestian56
Copy link

Having the same issue

@mateo2708
Copy link

mateo2708 commented Aug 13, 2019

I'm having the exact same issue.

@TLadd
Copy link
Contributor

TLadd commented Aug 16, 2019

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.

@hwillson hwillson self-assigned this Aug 19, 2019
@mtsamis2
Copy link

Having the same issue as well.

@eltonio450
Copy link

@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).

@mpgon
Copy link

mpgon commented Sep 4, 2019

Same. And no-cache "works" indeed.

@eltonio450
Copy link

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 :)

@mpgon
Copy link

mpgon commented Sep 4, 2019

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>
  );
};

@hwillson
Copy link
Member

hwillson commented Sep 6, 2019

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

@hwillson hwillson removed their assignment Sep 6, 2019
@jeffal
Copy link

jeffal commented Sep 6, 2019

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"

@mddilley
Copy link

mddilley commented Sep 7, 2019

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" }
  );

@mpgon
Copy link

mpgon commented Sep 10, 2019

@hwillson I tried updating to 3.1.0 but I got this problem: #3482

@hwillson
Copy link
Member

Is anyone still seeing this issue with React Apollo 3.1.0?

@mpgon
Copy link

mpgon commented Sep 16, 2019

Not so far :)

@hwillson
Copy link
Member

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

@mpgon
Copy link

mpgon commented Sep 25, 2019

@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.

@emilsjolander
Copy link

emilsjolander commented Oct 10, 2019

@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.

@ajhool
Copy link

ajhool commented Oct 28, 2019

@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

@dvester
Copy link

dvester commented Oct 31, 2019

I can confirm this is still occurring in 3.1.3.

@davetapley
Copy link

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 😞

@mpgon
Copy link

mpgon commented Nov 8, 2019

@hwillson can you re-open this issue?

@br-dev
Copy link

br-dev commented Nov 14, 2019

I seem to have this same issue with @apollo/client 3.0.0-beta.7. I'm running on react-native (expo) while connected to the React Native Debugger. If I disconnect from the debugger, I don't seem to have this issue. The version of React Native Debugger I'm using is 0.10.2. Perhaps this issue is with RND?

@hamzakubba-opendoor
Copy link

hamzakubba-opendoor commented Dec 5, 2019

I found a workaround for 3.1.3, which is to set { pollInterval: 0 } as an option. Not sure why it fixes it, but seems to do so consistently for me.

@nhuesmann
Copy link

I just encountered this issue as well in 3.1.3... @hwillson can you reopen this issue?

@robotzhang
Copy link

we can fixed it with follow code:

...
const client = React.useRef(query.client());
const { data, loading, error } = useQuery(`GQL`, {
  variables,
  client: client.current,
});
...

@yairtal
Copy link

yairtal commented Dec 12, 2019

I am having the same issue, major blocker

@hashk99
Copy link

hashk99 commented Dec 12, 2019

I have the same issue and had to use fetchPolicy: 'no-cache', as a tempory solution

@beeglebug
Copy link

beeglebug commented Dec 16, 2019

This is definitely still happening in 3.1.3.

Having to add fetchPolicy: 'no-cache' is not a viable long term solution.

Please re-open this issue.

@jesster2k10
Copy link

I have the same issue too, I can't fetch data when using anything with network and hooks

@ajhool
Copy link

ajhool commented Dec 28, 2019

I've submitted a new issue to request that this issue be reopened.

#3774

@micro9000
Copy link

I have I think the same issue right now,
the loading is false when the fetching is done and the data has the return data from useQuery
but when I try to access the object inside the data, it throws an error that the data is undefined

so for example, my code is

const { data, loading, error } = useQuery(GET_ALL_PROJECTS_BY_CURRENT_USER);

if (!loading){
    console.log(data); // I have the data
    // but when I try to access the projects object
    console.log(data.projects); // it throws an error that the data is undefined
}

@bighitbiker3
Copy link

I don't know how to explain this, but I have this happen when a totally different async function on the same page fails. No idea why/how, but fixing that random promise rejection fixed this for me

@eltonio450
Copy link

What you describe reminds me this old thread from Dan Abramov : https://mobile.twitter.com/dan_abramov/status/770914221638942720?lang=en

@etiennelunetta
Copy link

Encountered issue on 3.1.3

@jesuslopezlugo
Copy link

I have the same issue on 3.1.3.

I tried fetchPolicy: "no-cache" and pollInterval: 0 on my useQuery hook without success 😢

@orrybaram
Copy link

Upgrading to 3.1.3 fixed the issue we were seeing.

@dimitarrusev
Copy link

Experiencing the same issue on 3.1.3.

@ivan-kleshnin
Copy link

ApolloClient 3.0.0-beta.

In my case useQuery hangs when the Apollo server responds with [Error: Page.fieldName defined in resolvers, but not in schema].

@pierreferry
Copy link

What you describe reminds me this old thread from Dan Abramov : https://mobile.twitter.com/dan_abramov/status/770914221638942720?lang=en

This comment helped me a lot ! Thx !!

I had the following issue :
When having an error in the request, my useQuery hook was always loading.

const { loading } = useQuery(myQuery);
console.log(loading); // always true when myQuery fails

The issue was created, not by react-apollo, but by the way we wrote onError in ApolloClient. For some reason we were doing this throw new GraphQLErrors(errorObject); after all of our custom handling (user not logged-in, etc...).

I solved this by removing throw new GraphQLErrors(errorObject); and loading is working properly, even after an error.

@samrith-s
Copy link

Same issue with @apollo/client@3.0.0-beta.44.

@Amirault
Copy link

same on :
"@apollo/react-components": "3.1.5",
"@apollo/react-hoc": "3.1.5",
"@apollo/react-hooks": "3.1.5",

"apollo-cache": "1.3.4",
"apollo-cache-inmemory": "1.6.5",
"apollo-client": "2.6.8",

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

No branches or pull requests