React query + storage-persister: Different result on development and production builds. #6138
Send to my agentDescribe the bug#
I prepared repository with the issue.
I have NextJS app and I can see that combination of React query + storage-persister works different on dev and prod builds.
[Development mode]: When you set 2 keys to react query - it's reflected to persister storage (localstorage) [Production mode]: When you set 2 keys to react query - first key reflected to persister storage (localstorage)
Here is my setup.
constants/react-query.ts
import { QueryClient } from "@tanstack/react-query";
import { createSyncStoragePersister } from "@tanstack/query-sync-storage-persister";
export const queryClient = new QueryClient({
defaultOptions: {
queries: {
retry: false,
refetchOnWindowFocus: false,
cacheTime: 1000 * 60 * 60 * 24, // 24 hours
refetchOnMount: false,
refetchOnReconnect: false,
},
},
});
export const persister = createSyncStoragePersister({
key: "OFFLINE_KEY",
storage: typeof window !== "undefined" ? window.localStorage : undefined,
serialize: (data) => {
console.log("serialize", data);
return JSON.stringify(data);
},
deserialize: (data) => {
console.log("deserialize", data);
return JSON.parse(data);
},
});
_app.tsx
import React, { ReactElement, ReactNode } from "react";
import type { AppProps } from "next/app";
import { NextPage } from "next";
import { PersistQueryClientProvider } from "@tanstack/react-query-persist-client";
import { persister, queryClient } from "constants/react-query";
...
function MyApp({ Component, pageProps }: AppPropsWithLayout) {
...
return (
<>
<PersistQueryClientProvider
client={queryClient}
persistOptions={{ persister }}
>
<Component {...pageProps} />
...
</PersistQueryClientProvider>
</>
);
}
export default MyApp;
pages/index.tsx
import { useQuery } from "@tanstack/react-query";
import { queryClient } from "constants/react-query";
import { NextPageWithLayout } from "pages/_app";
import { v4 } from "uuid";
enum QueryKeys {
CHATS = "chats",
ACTIVE_CHAT = "active-chat",
}
export const askQuestion = (question: string) => {
const newActiveChat = v4();
queryClient.setQueryData<any>([QueryKeys.CHATS], (chats = {}) => ({
...chats,
[newActiveChat]: question,
}));
queryClient.setQueryData<string | null>(
[QueryKeys.ACTIVE_CHAT],
newActiveChat
);
};
const HomePage: NextPageWithLayout = () => {
const { data } = useQuery([QueryKeys.CHATS]);
const { data: activeChat } = useQuery<string>([QueryKeys.ACTIVE_CHAT]);
const setData = () => {
askQuestion("Need help");
};
return (
<div>
<div>
Active chat - {activeChat}
{JSON.stringify(data)}
</div>
<button className="btn" onClick={setData}>
Set data
</button>
</div>
);
};
export default HomePage;
Your minimal, reproducible example#
https://github.com/Ilya-Valasiuk/react-query-persister-issue
Steps to reproduce#
npm inpm run build && npm run start- open http://localhost:3000/
- Click 'Set data' button
Check localstorage for OFFLINE_KEY key. It's gonna be different that actual status for react query. To check actual status - open console and do window.toggleDevtools(). You can see that react query have 2 keys but in persistance storage we have only 1.
The issue reproducable only on production build.
If you cleanup localstorage and run npm run dev - working as exptected.
Expected behavior#
As a user I expect to see the same behaviour on production as I see on development. If react query cache updated - persist storage should reflect to it and have the same data.
How often does this bug happen?#
Every time
Screenshots or Videos#
https://github.com/TanStack/query/assets/4801973/4ae7557f-befc-491f-ba5a-34a31d75b036
Platform#
- OS macos 14.0
- Chrome, Safari
Tanstack Query adapter#
react-query
TanStack Query version#
v4.36.1
TypeScript version#
v4.9.4
Additional context#
Looks like we can't do multiple setQueryData on production. Only first one reflected to persister storage.
TkDodo added labelsbug
TkDodo added labelspackage: sync-storage-persister
interestingly, if you use the
asyncStoragePersisterplugin, it works. Probably because theasyncThrottlefunction works differently.If I run that function through
terser, I get this output:export function throttle(t,l=100){let n,u=null;return function(...e){n=e,null===u&&(u=setTimeout((()=>{t(...n),u=null}),l))}}we can clearly see it keeps the
n=eassignment in there 🤔So I looked deeper into this, and I realized that the bundling is not happening on our end - we just provide the sources, and your framework (nextJs) does the bundling. Knowing that, I verified that the same example works in a
viteapp. This indicates that the issue is nextJs specific, and indeed, if I setswcMinify:falseinnext.config.js, which you have set totruein your example, the code works like it should.This means case closed on our end, but I would urge you to raise an issue on either nextJs or swc's side. Feel free to use our throttle function as an example.
A quick check in the swc playground also couldn't reproduce the issue, but its impossible to tell which options are being used by nextJs.
TkDodo closed this
TkDodo added labelsupstream
@TkDodo Sounds good! thank you for your time!
I've updated NextJS from
13.4.4to13.5.4and issue resolved. Looks like we've caught broken build from NextJS :(.
Sign in to join this conversation.
interesting issue for sure, thanks for reporting. It seems like there's something weird going on with how the
throttlefunction is transpiled. Per default, we throttle writes to one write per second, but we are still capturing the latest params. The code is this:https://github.com/TanStack/query/blob/13b17ee45de3299dd3d3a2dfc3d23ad2f024882a/packages/query-sync-storage-persister/src/index.ts#L95-L110
So we schedule a timeout that calls the original function, but we capture the latest
argsby storing them inparams, and then usefunc(...params)to invoke func with the latest args. Nowargsis the serialized query cache, so when multiple writes happen within the throttle time, theparams=argsis what will actually give you the latest version (the one with two queries).However, it seems that in production, this becomes:
Here, I just see
t(...n)- the whole capturing ofargsin theparamsvariable is gone. Probably it got inlined for some reason. That means you'll get the actual persistence call invoked with the first params, not the latest ones.I tried upgrading to v5 because we use a different bundler there (tsup) but the result is the same.