PersistQueryClientProvider is not working with suspense query #6148
Send to my agentDescribe the bug#
PersistQueryClientProvider is not working with suspense query
Your minimal, reproducible example#
https://codesandbox.io/s/suspense-persistqueryclientprovider-bug-qdy8cz
https://snack.expo.dev/@manhhavu/persistentqueryclientprovider-suspense-bug
Steps to reproduce#
I have to say sorry in advance that I tried to reproduce it with Expo Snack but there is some strange behavior in module resolution on Snack that the app couldn't even run. You can checkout the reproducible bug from this repo to fully see the problem.
I'm using useSuspenseQuery with rc12 version. If I only use QueryClientProvider, Suspense is working, the fallback of Suspense is shown while waiting for the data. When the data is available, the related component is render.
export default function App() {
return (
<QueryClientProvider
client={queryClient}
>
<View style={styles.container}>
<Suspense fallback={<ActivityIndicator />}>
<Todo />
</Suspense>
</View>
</QueryClientProvider>
);
}
function Todo() {
const { data: todo } = useTodo()
return (
<View style={{flexDirection: 'row'}}>
<Checkbox
value={todo.completed}
style={{alignSelf: 'center'}}
/>
<Text style={{marginLeft: 8}}>{todo.title}</Text>
</View>
)
}
function useTodo() {
return useSuspenseQuery({
queryKey: ['todo'],
queryFn: async () => {
return await fetchTodo()
}
})
}
if I change the config to use PersistQueryClientProvider instead of QueryClientProvider:
export default function App() {
return (
<PersistQueryClientProvider
persistOptions={{ persister: persister }}
client={queryClient}
>
<View style={styles.container}>
<Suspense fallback={<ActivityIndicator />}>
<Todo />
</Suspense>
</View>
</PersistQueryClientProvider>
);
}
then this part of Todo is supposed to suspended until the data is available, but it is isn't:
function Todo() {
// should suspense here so that the todo object is not null before continuing
// but it isn't the case.
const { data: todo } = useTodo()
// ...
}
The data/todo object is null which will fail the code below which tries to access it.
Expected behavior#
The behavior of PersistQueryClientProvider should be identical to QueryClientProvider regarding Suspense query.
How often does this bug happen?#
Every time
Screenshots or Videos#
No response
Platform#
- OS: iOS 17 on macOS Ventura 13.6
- Expo: 49
Tanstack Query adapter#
react-query
TanStack Query version#
v5.0.0-rc.12
TypeScript version#
No response
Additional context#
No response
manhhavu(GitHub profile, opens in a new tab) changed the title
TkDodo added labelspackage: react-query-persist-client
TkDodo added labelssuspense
@TkDodo :
can you please create a reproduction that doesn't involve react native? Because the issue is definitely not react-native specific.
Here is the web-only reproduction: https://codesandbox.io/s/suspense-persistqueryclientprovider-bug-qdy8cz?file=/src/App.js . Tell me if you need anything.
What you can do on your end is to opt into a custom PersistGate that will block your app from rendering (and thus your queries from running):
Thank you for the workaround. It is indeed working. Hopefully you will be able to come up with a solution 😅.
Here is the web-only reproduction
Thank you 🙏
I think the PersistGate is a pretty good solution. The only other thing that comes to my mind is throwing a Promise that resolves when
isRestoringcomes back tofalse, so that the suspense fallback shows instead. I'm not sure if you'd actually want to render a loading spinner (=the suspense fallback) while restoring from external storage. At least with the PersistGate, you have a differentiation between actually running the queryFn and restoringTkDodo added labelsbug
Yes, I don't mind using the PersistGate.
I'm not sure if you'd actually want to render a loading spinner (=the suspense fallback) while restoring from external storage
To be honest, from app users' point of view, whether it is loading from external storage or an HTTP API, they should be transparent to them. If the data isn't available, users should see the fallback displayed. But of course, it is just my opinion, you should take it with a grain of salt 😅
If the data isn't available, users should see the fallback displayed.
yeah, I'll think about it. You can use the
PersistGateto render the same fallback as the suspense boundary, so at least we're covered there. But I can see that it becomes tedious if you have fine-grained suspense boundaries sprinkled in your app, and if you'd want that, you'd need to add lots of PersistGates as well, potentially one for each Suspense Boundary.I'll think about if throwing a different Promise while restoring is a good idea. It won't be a breaking change so there's no rush, and we have the workaround for now 👍
TkDodo added labelshas workaround
we're now suspending whenever we have no data so that
datareturned fromuseSuspenseQuerywill always be defined. This should also fix this this issue. see:TkDodo closed this
@TkDodo thanks for the solution, but I want to confirm if I understand it correctly.
- Use
PersistGate
The first option is to use
PersistGatein order to make it work (Suspense+PersistQueryClientProvider)<PersistGate fallback={<AccountDetailsSkeleton />}> <ErrorBoundary fallback={<AccountDetailsFallback />}> <Suspense fallback={<AccountDetailsSkeleton />}> <AccountDetails /> </Suspense> </ErrorBoundary> </PersistGate>In this case I need to wrap each
Suspensein my app withPeristGate?- Throwing a Promise
I'll think about if throwing a different Promise while restoring is a good idea... (c) TkDodo
I didn't understand what do you mean by this?
P.S. I also wondering if using a
PersistQueryClientProvideris a required option?For instance, if I do this
import { createSyncStoragePersister } from "@tanstack/query-sync-storage-persister"; import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; import { ReactQueryDevtools } from "@tanstack/react-query-devtools"; import { PropsWithChildren } from "react"; const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false, gcTime: 1000 * 60 * 60 * 24, // 24 hours }, }, }); const localStoragePersister = createSyncStoragePersister({ storage: window.localStorage, }) persistQueryClient({ queryClient, persister: localStoragePersister }) export function ReactQueryProvider(props: PropsWithChildren) { return ( <QueryClientProvider client={queryClient}> {props.children} <ReactQueryDevtools initialIsOpen={false} /> </QueryClientProvider> ); }The
useSuspenseQueryworks correctly without usingPersistGate. So, what is the drawback of using such approach? (I read the documentation, but didn't understand it)- Use
In this case I need to wrap each Suspense in my app with PeristGate?
I would wrap the whole app in one PersistGate, but yes, multiples should also work.
I didn't understand what do you mean by this?
That would've been something we could do internally. Nothing for you to do here.
So, what is the drawback of using such approach?
drawbacks are listed here: https://tanstack.com/query/v5/docs/react/plugins/persistQueryClient#usage-with-react
we're now suspending whenever we have no data so that
datareturned fromuseSuspenseQuerywill always be defined. This should also fix this this issue. see:Thanks for this - should the PersistQueryClientProvider be working without needing the PersistGate or have I read this wrong? I'm currently seeing fetches repeated with using Suspense without the PersistGate
yes it should work
@TkDodo thanks for the solution, but I want to confirm if I understand it correctly.
- Use
PersistGate
The first option is to use
<PersistGate fallback={}> <ErrorBoundary fallback={}> <Suspense fallback={}> In this case I need to wrap each `Suspense` in my app with `PeristGate`?PersistGatein order to make it work (Suspense+PersistQueryClientProvider)- Throwing a Promise
I'll think about if throwing a different Promise while restoring is a good idea... (c) TkDodo
I didn't understand what do you mean by this?
P.S. I also wondering if using a
PersistQueryClientProvideris a required option?For instance, if I do this
import { createSyncStoragePersister } from "@tanstack/query-sync-storage-persister"; import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; import { ReactQueryDevtools } from "@tanstack/react-query-devtools"; import { PropsWithChildren } from "react";
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false, gcTime: 1000 60 60 * 24, // 24 hours }, }, });
const localStoragePersister = createSyncStoragePersister({ storage: window.localStorage, })
persistQueryClient({ queryClient, persister: localStoragePersister })
export function ReactQueryProvider(props: PropsWithChildren) { return ( {props.children} ); } The
useSuspenseQueryworks correctly without usingPersistGate. So, what is the drawback of using such approach? (I read the documentation, but didn't understand it)Facing an error: "localStorage not defined" if I use second solution
- Use
Facing an error: "localStorage not defined" if I use second solution
then check for
window.localStorageon the server and pass undefined tostorage.
Sign in to join this conversation.
I tried to run the example in codesandbox but it doesn't really work there either: https://codesandbox.io/p/github/manhhavu/persister-bug/main?file=%2FApp.js%3A1%2C1
can you please create a reproduction that doesn't involve react native? Because the issue is definitely not react-native specific.
With the PersistQueryClientProvider, we've opted to continue to render the application while the queries are restoring from the external storage (we just don't run the queryFn, we keep the query in an
idlestate) instead of blocking the whole rendering with aPersistGate, like e.g. redux-persist does. That makes sure pages can server-render, which you couldn't with a Gate.This works fine with normal queries, they will render in
status: 'pending'andfetchStatus: 'idle', and data will be undefined. That's fine because you have to handle that state anyways. When data comes back from the storage, we re-render with that data and potentially re-run the queryFn if that data is stale.However, with suspense, we'd expect
datato be defined as soon as we passuseSuspenseQuery, because the suspense fallback should be rendered instead. We don't do that though because of the state we keep the query in as mentioned above.So now your app renders with
undefineddata and that's not good. I'll have to look into what we can do here. One idea is to throw to the suspense boundary, but we can't really do that because we have noPromise. We don't want to trigger the queryFn before restore has been completed. I need to think about this.What you can do on your end is to opt into a custom
PersistGatethat will block your app from rendering (and thus your queries from running):put that inside the Provider, but around your app:
this should work around the issue