Skip to content
Source
Sign inSign up
TanStack/query

Cannot overwrite dataUpdatedAt if Date.now is smaller then in the cache already #9724

ClosedGitonioDev(GitHub profile, opens in a new tab) opened this issue 8 comments

Describe the bug

Hello there, im using Server Side Rendering with React Query and im testing out some stuff i noticed if i manually change the time in the browser to a past time then react query will never update a the query that was dehydrated because its considered as not stale, to avoid that i would like to update all queries that the server dehydrated on app mount, what should be updated? well the dataUpdatedAt to the current Date.now(). when trying to implement a similar thing:

useOnMount(() => {
    console.log("App Mounted");
    if (!dehydratedState) return;
    console.log("Hydrating Query Client with Dehydrated State");
    dehydratedState.queries.forEach((query) => {
        console.log("Setting query data for:", query.queryKey, query.state.data, Date.now());
        queryClient.setQueryData(query.queryKey, query.state.data);
    });
});

This works well if the client time is higher then the initial server time but doesnt work if the client time is lower then the initial server time

Your minimal, reproducible example

Steps to reproduce

  1. Create a blank react query + ssr project
  2. dehydrate data on the server with correct time
  3. change browser time to the past
  4. loop over all dehydrated queries and call setQueryData for each of them to try to update the updatedAt

Expected behavior

I would expect / request to have a option to do like { force: true } so it will not check if the Date.now() is smaller then the already existing dataUpdatedAt, it just overwrites it

How often does this bug happen?

Every time

Screenshots or Videos

No response

Platform

  • OS Windows
  • Browser Firefox

Tanstack Query adapter

react-query

TanStack Query version

5.83.0

TypeScript version

5.8.3

Additional context

No response

  1. TkDodocommented

    This is on purpose. If data from the server is older than what you already have in the cache, we won’t overwrite it. Otherwise, cached data on the server might overwrite fresher data on the client.

    setQueryData on the other hand is unconditional. If you call it, data will be set.

  2. TkDodo closed this

  3. TkDodo added labelsworks as designed

  4. So if a client has past time configured then the initial page / query that got loaded via dehydration will never be refetched, is that right, because data is considered as always fresh? if that is expected then i would stop banging my head to get around this

  5. TkDodocommented

    usually the client has no data when you do SSR, so if you send data from the server the first time, it will always be taken.

    it’s also documented here: https://tanstack.com/query/latest/docs/framework/react/guides/ssr#staleness-is-measured-from-when-the-query-was-fetched-on-the-server

    so in order to see your described issue you would need to:

    • initially SSR data (will be put in the cache)
    • do a refetch from the client (now you have data that has client timezone data)
    • now re-trigger SSR (are we talking server components, gSSP in pages router, idk?) and if you now get data that is older than what your client has, it will be discarded.

    Is that what you’re seeing?

  6. no i initially ssr data the data is put into the cache the server lives in the normal time, the client however is configured with a past time so ssr data (higher time) is put into the client if i now navigate client sidely pure react query then the data in the client will always be considered as fresh and will never refetch, thats the problem i currently have if the client has a past configured time the client will never see a refetch for the data that got put into the cache from a higher dehydrated time

    So all in all my server only feeds the client on the very initial render every navigation afterwards should be handled by the client to properly cache content

  7. i guess thats kinda expected its a client problem to not take over the server data correctly

  8. TkDodocommented

    the only issue I could see here is different timezones, but as the docs say, that shouldn’t be a problem:

    A query is considered stale depending on when it was dataUpdatedAt. A caveat here is that the server needs to have the correct time for this to work properly, but UTC time is used, so timezones do not factor into this.

  9. oohhh nonono i mean if the client time is just completly false so like 5 hours behind the real clock

  10. Fixed it by changing the default behavoir to take over the updatedAt on the client and not from the server, and also i think this makes more sense because lets say the server takes long time to respond but the prefetchQuery was fast as soon as the data lands in the client it will directly be stale because of that time gap, the client should say oh here is my data im gonna do now stuff with it, this also supports the client time to be broken, what was the reason to take the updatedAt from the server onto the client? just because the server maybe fetched data before it sended it? i dont see a reasonable reason it would also avoid wrongly configured time to still work without a problem, because the client controls that time.

    Just a feature request, maybe have a option in the dehydrate options to opt out of staleness-is-measured-from-when-the-query-was-fetched-on-the-server so this would make it support broken client times and would not break the app if the client has a wrong time configured

    So there are two ways

    • staleness-is-measured-from-when-the-query-was-fetched-on-the-server: Good for that one reason but risky for wrongly configured times either server or client
    • staleness-is-measured-from-when-the-query-arrived-on-the-client: Simple, supports broken times and just works like a client cache, and thats my thoughts on that, a client cache should take the date from the client and not from the server. This is just my point of view
    import type { DehydratedState } from "@tanstack/react-query";
    import merge from "deepmerge";
    import { useMatches } from "react-router";
    import { useEffect, useRef, useState } from "react";
    
    function buildMerged(dehydratedStates: DehydratedState[]): DehydratedState | undefined {
        if (dehydratedStates.length === 0) return undefined;
        const merged: DehydratedState = dehydratedStates.reduce<DehydratedState>((acc, curr) => merge(acc, curr), {
            queries: [],
            mutations: [],
        });
        if (merged.queries) {
            merged.queries.forEach((query) => {
                if (query?.state?.dataUpdatedAt) {
                    console.log("Forcing dataUpdatedAt to now for queryKey:", query.queryKey);
                    query.state.dataUpdatedAt = Date.now();
                }
            });
        }
        return merged;
    }
    
    function areStatesEqual(a: DehydratedState[] | undefined, b: DehydratedState[] | undefined): boolean {
        return JSON.stringify(a) === JSON.stringify(b);
    }
    
    export function useDehydratedState(): DehydratedState | undefined {
        const matches = useMatches();
    
        const dehydratedStates: DehydratedState[] = matches
            .map((match) => (match.loaderData as any)?.dehydratedState as DehydratedState | undefined)
            .filter((state): state is DehydratedState => Boolean(state));
    
        const [normalized, setNormalized] = useState<DehydratedState | undefined>(() => buildMerged(dehydratedStates));
        const prevStates = useRef<DehydratedState[] | undefined>(dehydratedStates);
    
        useEffect(() => {
            if (!areStatesEqual(prevStates.current, dehydratedStates)) {
                setNormalized(buildMerged(dehydratedStates));
                prevStates.current = dehydratedStates;
            }
        }, [dehydratedStates]);
    
        return normalized;
    }
    

Sign in to join this conversation.