T
TanStack17mo ago
fascinating-indigo

Persistence fails after query client gets changed

In a React Native application I want to only call the API when the user is logged in. This requires me to create a query client that is enabled or disable based on the auth state. I am pretty sure this causes the PersistQueryClientProvider to not work properly since the query client changes. I only get persistence on initial app load, but when the app state changes to logged in persistence stops working. Is there a workaround for this? https://github.com/BeBoRE/ei-noah-bot/blob/c70e1ba851de5f45479d75d33177bcad8dde1286/apps/mobile/src/utils/api.tsx
GitHub
ei-noah-bot/apps/mobile/src/utils/api.tsx at c70e1ba851de5f45479d75...
De officiële Discord Bot voor de Sweaty GG Chat. Contribute to BeBoRE/ei-noah-bot development by creating an account on GitHub.
1 Reply
fascinating-indigo
fascinating-indigoOP17mo ago
For now I have just fixed it by doing the subscribing and unsubscribing myself, instead of letting the provider do it.
const [queryClient, unsubscribe] = React.useMemo(() => {
const queryClient = new QueryClient({
defaultOptions: {
queries: {
staleTime: 2000 * 1,
enabled: isLoggedIn,
gcTime: 1000 * 60 * 60 * 24 * 7,
retry: (retryCount, err) => {
if (
err instanceof TRPCClientError &&
err.data?.httpStatus === 401
) {
return false;
}

return retryCount < 3;
},
},
},
queryCache: new QueryCache({
onError: (err) => {
if (err instanceof TRPCClientError) {
onError(err);
}
},
}),
mutationCache: new MutationCache({
onError: (err) => {
if (err instanceof TRPCClientError) {
onError(err);
}
},
}),
});

const persister = createAsyncStoragePersister({
storage: AsyncStorage,
serialize: superjson.stringify,
deserialize: superjson.parse,
});

const [unsubscribe] = persistQueryClient({
queryClient,
persister,
maxAge: 1000 * 60 * 60 * 24 * 7,
});

return [queryClient, unsubscribe];
}, [isLoggedIn, onError]);

useEffect(
() => () => {
unsubscribe();
},
[unsubscribe],
);
const [queryClient, unsubscribe] = React.useMemo(() => {
const queryClient = new QueryClient({
defaultOptions: {
queries: {
staleTime: 2000 * 1,
enabled: isLoggedIn,
gcTime: 1000 * 60 * 60 * 24 * 7,
retry: (retryCount, err) => {
if (
err instanceof TRPCClientError &&
err.data?.httpStatus === 401
) {
return false;
}

return retryCount < 3;
},
},
},
queryCache: new QueryCache({
onError: (err) => {
if (err instanceof TRPCClientError) {
onError(err);
}
},
}),
mutationCache: new MutationCache({
onError: (err) => {
if (err instanceof TRPCClientError) {
onError(err);
}
},
}),
});

const persister = createAsyncStoragePersister({
storage: AsyncStorage,
serialize: superjson.stringify,
deserialize: superjson.parse,
});

const [unsubscribe] = persistQueryClient({
queryClient,
persister,
maxAge: 1000 * 60 * 60 * 24 * 7,
});

return [queryClient, unsubscribe];
}, [isLoggedIn, onError]);

useEffect(
() => () => {
unsubscribe();
},
[unsubscribe],
);

Did you find this page helpful?