T
TanStack11mo ago
eastern-cyan

Custom query persist and Network error leading to removal of stale data from storage.

In React Native with TanStack Query V5, we persist query data to secure storage using createAsyncStoragePersister with the React Native Keychain library. The stale time is 15 minutes, and the maximum age for persisted data is 28 days. Scenario: GIVEN stale time elapsed, the query has stale data and the mobile device is offline, WHEN the App is cold-opened 1st, 2nd ... nth time, THEN App should display stale data. ACTUAL: Firstime: The query attempts to fetch new data in offline mode, this fetch results in a NETWORK_ERROR response, the screen continues to display the stale data, and in the background the persistor is triggered (Why?), which removes the data associated with that key. (cache is not 1:1 anymore with persistor) Second-time: when the app is opened next time in offline mode, no data is available for that key anymore. Why does this happen? I would expect Persistor not to get triggered. WORKAROUND: I have added an "enabled" option to that query with the boolean "isConnected" from React Native Net Info. Now, it does not trigger the API fetching call if the device is offline, and the Persistor does not get triggered.
1 Reply
afraid-scarlet
afraid-scarlet11mo ago
Per default, only queries in success state are persisted. If you get a query into error state, even if it has stale data, it will no longer be synced. You can customize what gets synced with the shouldDehydrateQuery option

Did you find this page helpful?