query icon indicating copy to clipboard operation
query copied to clipboard

useQuery return always isLoading with true when enabled is false

Open aXenDeveloper opened this issue 4 years ago • 37 comments

Describe the bug

When I created useQuery with enabled: false option, isLoading variable is always true.

Your minimal, reproducible example

https://codesandbox.io/s/react-query-enabled-7u58d5-7u58d5

Steps to reproduce

  1. Create simple query by use useQuery,
  2. Add enabled: false into options,
  3. Check state for isLoading.

Expected behavior

State isLoading is false.

How often does this bug happen?

Every time

Screenshots or Videos

image

Platform

  • OS: Windows 11 22H2,
  • Browser: Chrome
  • Version: 103

react-query version

4.0.10

TypeScript version

4.7.4

Additional context

No response

aXenDeveloper avatar Aug 03 '22 09:08 aXenDeveloper

Ok, I see this https://tanstack.com/query/v4/docs/guides/disabling-queries Its very strange...

aXenDeveloper avatar Aug 03 '22 09:08 aXenDeveloper

I faced the same! react-query version 4.0.10

  const { isLoading } = useQuery(
    ['currentUser'],
    () => Promise.resolve(),
    {
      enabled: false, // always false just for test
    }
  );

// isLoading is always true 

It seems to me I have to downgrade till it's fixed

UPD: https://tanstack.com/query/v4/docs/guides/disabling-queries

If the query does not have cached data
The query will start in the status === 'loading' and fetchStatus === 'idle'

Are you serious ? It's it a correct behaviour? In other words I should check fetchStatus or enabled additionally ... But why? in v3 the behaviour was absolutely predictable.

egorovsa avatar Aug 04 '22 11:08 egorovsa

Not that your comment would deserve another answer, but see: https://tanstack.com/query/v4/docs/guides/queries#why-two-different-states

TkDodo avatar Aug 04 '22 13:08 TkDodo

@TkDodo I appreciate your answer thanks a lot, however, this behaviour of isLoading is unpredictable at least because the hook says that it is loading smth and the status is loading as well whereas in fact it's loading nothing and just waiting for to be enabled. In a similar topic you noticed about isPending it seems to me it would be more logic.

egorovsa avatar Aug 04 '22 13:08 egorovsa

Yes, in hindsight, I also think that pending / success / error would be the better naming for the states. We thought about it, but decided that it would break too many cases / cause troubles upgrading.

If you have previously checked for the idle state explicitly, you now have to combine two checks. We can talk about exposing an extra derived flag if we find a good name for it.

often, you can:

  • check for data availability over checking statuses, as this will make your behavior more predictable. I have a blogpost on that topic: https://tkdodo.eu/blog/status-checks-in-react-query
  • for dependent queries, it is often good enough to keep checking the loading state, because if you're interested in data for the second query, you need to wait for it anyhow.

Maybe you can show your use-case and we can try to come up with the best way of handling it without checking both flags combined.

Lastly, v4 was in alpha / beta for about 6 months. Feedback on api changes is most effective during that time, before we released v4.0. "Are you serious?" comments when it's too late to change something are not helpful. So yes, I'm serious.

TkDodo avatar Aug 04 '22 16:08 TkDodo

This also caused a bug when I upgraded. For my use case I have a list of email threads on the left side and the current thread on the right side. The right side should show an empty state when no thread is selected, and a loader once a thread has been selected and is fetching the data for that thread.

We just used 'isLoading' to check if we should show a loader or not, and that made the right side show a loader constantly until a thread was selected, instead of an empty state. A flag that tells us when to show the loader in these cases would be a lot cleaner than having to check if fetchStatus is not idle and if it's loading, or if there's no data present, etc. 🤷

parkm avatar Aug 04 '22 17:08 parkm

A flag that tells us when to show the loader in these cases would be a lot cleaner than having to check if fetchStatus is not idle and if it's loading, or if there's no data present

showing data if data is there might be the best way, as this will prevent data unmounting if e.g. a background update yielded an error.

I mean, you could also not mount the current thread component if no thread is selected?

However, I'm happy to add that flag if we can find a good name for "isLoading and isFetching" ... isHardLoading ?

The right side should show an empty state when no thread is selected, and a loader once a thread has been selected and is fetching the data for that thread.

Just for my understanding: how did you implement this in v3? With an explicit isIdle check? Or did you just fall through all other cases and rendered null?

TkDodo avatar Aug 04 '22 18:08 TkDodo

Just for my understanding: how did you implement this in v3? With an explicit isIdle check? Or did you just fall through all other cases and rendered null?

So I have two queries, one for the thread list on the left, and one for the current thread. The current thread query is disabled until a thread has been selected.

So my logic was:

if (currentThreadQuery.isLoading) {
   showLoader()
} else if (!currentThreadQuery.data) {
   showEmptyState()
} else {
   showCurrentThread()
 }

Now I just have to change that first line to currentThreadQuery.isLoading && currentThreadQuery.fetchStatus !== 'idle' which isn't the end of the world, just a bit bulkier.

parkm avatar Aug 04 '22 18:08 parkm

@TkDodo I am sorry for the sharp expression like ""Are you serious?" at the same time I am not alone with this issue that faced a bug after update and was very upset after that.

Ok now about my case. This case is extremely simple

const { isLoading, data: currentUser, refetch, error } = useQuery(
    ['currentUser'],
    () => UsersApi.getCurrentUser(),
  );

  const { isLoading: isTokenLoading } = useQuery(
    ['tokenCoreApp'],
    () => UsersApi.getToken(),
    {
      enabled: Boolean(currentUser),
      onSuccess: handleTokenSuccess,
    }
  );

  const loading = isLoading || isTokenLoading;

First of all I have to get a current user data and token's query is depending on the current user. it means that it's possible that it will never be fired because the current user is 401.

Just why isTokenLoading should be true whenever this is switched off at all.

So now I just have to add an additional condition to have a common isLoading like this

isLoading || (isTokenLoading && Boolean(currentUser))

and I feel it looks ugly.

So it's confusing even in very simple example. BTW. about alpha and beta to my mind this is not an argument. I am not sure many people would test it on the projects those have already been in production for instance.

Have a good time. Thanks for your answers!

egorovsa avatar Aug 05 '22 06:08 egorovsa

@TkDodo we have also found issues with this new behaviour of isLoading.

If you have previously checked for the idle state explicitly, you now have to combine two checks. We can talk about exposing an extra derived flag if we find a good name for it.

What about including a new boolean flag isDisabled? Then isLoading would be false in cases where the query is disabled. In my opinion, it's a bit counter intuitive that a disabled query will return isLoading as true, because I'm not expecting it to load 😅

diegocasillas avatar Aug 11 '22 12:08 diegocasillas

What about including a new boolean flag isDisabled? Then isLoading would be false in cases where the query is disabled. In my opinion, it's a bit counter intuitive that a disabled query will return isLoading as true, because I'm not expecting it to load 😅

a query itself cannot be disabled. disabled on useQuery only means that this observer does not fetch data for itself. you can have two observers - on enabled one disabled, then the query will be fetching.

you can also have data on a query, because you prefetched it, hydrated it, restored it from localstorage or passed it as placeholderData/ initialData. in all these cases, the query would be in success state instead of loading.


I think it's mostly a mindset problem. I've tried to outline it in the docs as well: Think of loading / success / error as states that describe / discriminate the data property. If you think about a promise, it can be pending / fulfilled / rejected. That's the same concept. loading === pending - it just means "data is not here yet". It doesn't mean we're actually firing the queryFn to get the data right now - that's what the fetchStatus is for.


I think the best we could do is expose another flag that combines isLoading && !isFetching, which would be equivalent to the previous idle state. Finding a good name is the hardest part probably

TkDodo avatar Aug 11 '22 13:08 TkDodo

Thanks for your quick response! ✨ It makes a lot of sense and I agree that it's a mindset problem in our case. I'm still not sure what would be the best way of helping developers understand this change and migrate to this new version while keeping the behaviour we had previously with isLoading. I have a gut feeling that more people will find this an issue before they understand the underlying concept 🤔

I think the best we could do is expose another flag that combines isLoading && !isFetching, which would be equivalent to the previous idle state. Finding a good name is the hardest part probably

I wanted to be Captain Obvious here and suggest to name it isIdle, but I understand that it can't be "idle" if it is loading 😅

Thanks again ✌️

diegocasillas avatar Aug 11 '22 14:08 diegocasillas

I have a gut feeling that more people will find this an issue before they understand the underlying concept 🤔

I understand, and by now I think we should've just renamed loading to pending to make it more obvious, and maybe keep the isLoading flag around that also includes isFetching. But yeah, more feedback on the beta would've been good. Now it's too late :(

We can do: isInitialLoading: isLoading && isFetching but then you'd still need to check for that. It's the best I can come up with right now.

I wanted to be Captain Obvious here and suggest to name it isIdle, but I understand that it can't be "idle" if it is loading 😅

ha, I pondered about keeping the isIdle flag. The problem is that we also have a fetchStatus === "idle" and it would also be confusing if isIdle is not derived from that, like isPaused is derived from fetchStatus === "paused"

TkDodo avatar Aug 11 '22 14:08 TkDodo

I found this issue after running into the same issue and spending time debugging it. And tbh, I also had the same 'are you serious?' thought.

For a breaking change like this, I didn't find the word 'enabled' used in the doc Migrating to React Query 4. It would be helpful to include explicit instructions (e.g. a before&after code example) about how to migrate code with enabled: false in the guide.

anglee avatar Aug 15 '22 15:08 anglee

It would be helpful to include explicit instructions (e.g. a before&after code example) about how to migrate code with enabled: false in the guide.

It really depends on how you've checked for the idle state before. Did you use the isIdle flag? Did you use status === 'idle' ? Did you check for data availability and then fall back to rendering loading... if there is no data or error?

TkDodo avatar Aug 16 '22 07:08 TkDodo

Our team has been struggling with this as well and had had to work around this - normally by doing something like (isLoading && isEnabled) when deriving the true is loading state.

We have not looked into all the other properties to see if there is an easier way - but we were caught off guard that a disabled query shows up in a loading state and would love a simple boolean that we can use to know if a query is truly enabled and loading.

Maybe a name could be isEnabledAndLoading (that is at least how I think about things) Or isActivelyLoading

paustint avatar Aug 19 '22 19:08 paustint

Came across this one too. I agreed this is a mindset problem but mindset can be framed in many ways. most of our use case around enabled is to make a query run on a condition -- there's no guarantee that dependent query will always run.

Where the new behavior is more like -- dependent query will eventually run but it just don't have data yet and therefore is still consider as loading.

These are 2 different mental models and use cases. It's very unfortunate we made it as a breaking change without an easy migration plan in mind.

missing1984 avatar Sep 08 '22 23:09 missing1984

Just want to double check, since thinking about this stuff sometimes makes my head hurt.

Is the closest replacement to the previous behaviour of isLoading: isLoading && fetchStatus !== 'idle'?

ie:

import { useQuery } from '@tanstack/react-query' // react-query v4

const { isLoading, fetchStatus } = useQuery( ... )
const isLoadingV3 = isLoading && fetchStatus !== 'idle'

tomskopek avatar Sep 12 '22 17:09 tomskopek

Yes

TkDodo avatar Sep 12 '22 18:09 TkDodo

Long term, obviously I need to refactor my code to match the new isLoading mindset. On the one hand I don't want to create new variables called isLoading that are basically aliases for isLoading && fetchStatus !== 'idle', because that's confusing to have two meanings for isLoading and keep both in my mental model. On the other hand, I don't want to write out isLoading && fetchStatus !== 'idle' everywhere because it's not great for readabliity, and it's easy to forget that you also need to check that fetchStatus.

@TkDodo you seem receptive to adding a new variable to the return to capture the concept discussed above, if we can come up with a good name.

I had a look at the v3 documentation for the status: loading description. loading - if the query is in a "hard" loading state. This means there is no cached data and the query is currently fetching, eg isFetching === true

I'd like to throw another couple ideas into the ring:

isWaiting, or the more explicit isWaitingForData. This conveys appropriately that data has been fetched, but there is no data yet.

or:

initialFetchStatus. This would be the fetchStatus of the first fetch, but not subsequent ones. This one I am less sure about because of how caching works, someone more familiar with the library would have to ensure this makes sense.

or a variation of this, that would return a boolean (my preference):

isInitialDataLoading. I believe this fits the spirit of the v3 isLoading description? This means there is no cached data and the query is currently fetching

or:

isHardLoading. Simply because this is how v3 docs described it. Althought I don't find it terribly descriptive.

I also think @paustint 's suggestion of isEnabledAndLoading is not bad, although it's not quite the same as isLoading && fetchStatus !== 'idle', I think it's similar? Even if this is not a chosen direction, it would be useful to have an isEnabled boolean flag exposed in the return, so that we can standardize our queries.

Thoughts?

tomskopek avatar Sep 12 '22 20:09 tomskopek