Skip to content
Source
Sign inSign up
TanStack/query

React query + storage-persister: Different result on development and production builds. #6138

Send to my agent
ClosedIlya-Valasiuk(GitHub profile, opens in a new tab) opened this issue 6 comments

Describe 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

  1. npm i
  2. npm run build && npm run start
  3. open http://localhost:3000/
  4. 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.

  1. interesting issue for sure, thanks for reporting. It seems like there's something weird going on with how the throttle function 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 args by storing them in params, and then use func(...params) to invoke func with the latest args. Now args is the serialized query cache, so when multiple writes happen within the throttle time, the params=args is what will actually give you the latest version (the one with two queries).

    However, it seems that in production, this becomes:

    persistClient: function(t, e=100) {
      let i = null;
      return function(...n) {
        null === i && (i = setTimeout(()=>{
            t(...n),
              i = null
          }
          , e))
      }
    }

    Here, I just see t(...n) - the whole capturing of args in the params variable 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.

  2. TkDodo added labelsbug

  3. TkDodo added labelspackage: sync-storage-persister

  4. interestingly, if you use the asyncStoragePersister plugin, it works. Probably because the asyncThrottle function works differently.

  5. 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=e assignment in there 🤔

  6. 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 vite app. This indicates that the issue is nextJs specific, and indeed, if I set swcMinify:false in next.config.js, which you have set to true in 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.

  7. TkDodo closed this

  8. TkDodo added labelsupstream

  9. @TkDodo Sounds good! thank you for your time!

  10. I've updated NextJS from 13.4.4 to 13.5.4 and issue resolved. Looks like we've caught broken build from NextJS :(.

Sign in to join this conversation.