Skip to content
Source
Sign inSign up
TanStack/query

Data is lost from persister on refetch error #5112

Closedulyssesrr(GitHub profile, opens in a new tab) opened this issue 5 comments

Describe the bug

(Previously) persisted cache data is lost on refetch error, causing queryFn to run again on next usage of the App.

Your minimal, reproducible example

https://codesandbox.io/s/confident-beaver-fzqmer?file=/src/index.jsx

Steps to reproduce

Follow the on-screen steps :) which are:

  1. Start app, fetchFn is executed and data is persisted.
  2. Reopen app, data is retrieved immediately from persisted cache, no refetch depending on staleTime (2 min).
  3. Enable "Force fetch error", click "Refetch" and wait for it to fail. (Data is lost from persistent storage here)
  4. Reopen app, fetchFn is executed, as the persisted cache was lost, and data is persisted again.

("Clear localStorage" button allows to fully restart these steps, if needed)

Expected behavior

Since the in-memory cache is kept and the available data is still displayed on screen I intuitively expected the persisted cache to follow the same behavior, keeping the data it had, which would be the desired behavior for me. I couldn't find any documentation or config regarding this behavior. Thanks for your time.

How often does this bug happen?

Every time

Screenshots or Videos

No response

Platform

  • Reproduced on React Native (Android) and Browser (Brave)

Tanstack Query adapter

react-query

TanStack Query version

4.26.1

TypeScript version

No response

Additional context

No response

  1. This is expected. per default, only successful queries are stored:

    https://github.com/TanStack/query/blob/8e7a316c11924f239368cb076584cb255d5281fd/packages/query-core/src/hydration.ts#L72-L74

    If a query gets an error, it goes to error state, even if it has "stale" data to be shown. Now you can customize that to store all queries that have data, but keep in mind that Error is not json serializable, so after restoring, you'll have a query that is in error state, with data, but without an error, so accessing error.message will likely fail at runtime.

    You can use something like superjon to also serialize errors.

  2. TkDodo closed this

  3. TkDodo added labelsworks as designed

  4. TkDodo added labelspackage: react-query-persist-client

  5. Thank you for the explanation. I don't really want to persist the error state, in fact I believe my need is more a "data cache" than a "query cache". That is, I want to keep my data as long as the restrictions (gcTime\maxAge and etc...) are met, regardless of the last state of the query.

    I suppose I could implement a useQuery customization that saved the onSucess data and reused it in initialData, but then I would have to deal with the other caching aspects like busting, maxAge, etc...

    After considering these possibilities I wrote the following solution from the indications you gave me:

    function shouldDehydrateQuery(query) {
      return !_.isEmpty(query.state.data);
    }
    
    function clearDehydratedQueryError(dehydratedQuery) {
      // no way to restore previous errorUpdatedAt value
      // clean error state to keep state consistent
      const { state } = dehydratedQuery;
      const newState = {
        ...state,
        error: null,
        errorUpdatedAt: 0,
        errorUpdateCount: 0,
        fetchFailureCount: 0,
        fetchFailureReason: null,
        status: "success",
        // optionally flag that an error was discarded
        errorDiscarded: true
      };
      dehydratedQuery.state = newState;
    }
    
    function serialize(client) {
      client.clientState.queries
        .filter((q) => q.state.status === "error")
        .forEach(clearDehydratedQueryError);
      return JSON.stringify(client);
    }
    
    // optional: clear(do something) with errorDiscarded flag
    function deserialize(cachedString) {
      const cache = JSON.parse(cachedString);
      if (cache) {
        const client = cache;
        client.clientState.queries
          .filter((q) => q.errorDiscarded)
          .forEach((q) => {
            delete q.state.errorDiscarded;
          });
      }
      return cache;
    }
    
    const asyncStoragePersister = createAsyncStoragePersister({
      storage: localStorage,
      key: RQ_STORAGE_KEY,
      serialize,
      deserialize
    });

    This discards the error state when persisting, but it's a non-issue tor me, as I'm only interested in the data.

    Full solution here: https://codesandbox.io/s/quizzical-solomon-pp7koz?file=/src/index.jsx

    Its a bit hackish so I will do some more testing, but it seems to achieve what I wanted. It would be cleaner if dehydrateQuery were customizable like shouldDehydrateQuery, would you be interested in a PR for that?

    Once again, thanks for your time and this great library.

  6. It would be cleaner if dehydrateQuery were customizable like shouldDehydrateQuery, would you be interested in a PR for that?

    it's not a bad idea. Could be a function that adheres to the DehydratedQuery interface:

    https://github.com/TanStack/query/blob/8e7a316c11924f239368cb076584cb255d5281fd/packages/query-core/src/hydration.ts#L32-L36

    it's just that dehydrating excess properties wouldn't do anything because they would be ignored during hydration ...

  7. Hi @ulyssesrr ,

    Are you still using your original solution for the "data cache," or have you since found an alternative? I'm facing a similar challenge: I persist my getUser query, and I want the cached data to remain available even if a subsequent getUser request fails (for example, due to a network error) and the user reopens my app.

  8. @RRaideRR We are still using that solution in production with v4. If you are on v5 there may be a better solution.

Sign in to join this conversation.