Last active
November 17, 2024 02:20
-
-
Save hirbod/bc1538990d1b47419c3cb1f6622f7625 to your computer and use it in GitHub Desktop.
React Query Persister: clear stale data on boot (requires react-native-mmkvm runs on iOS, Android and Web)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export const useClearStalePersistedReactQueryData = () => { | |
useEffect(() => { | |
const threeDaysAgo = Date.now() - 3 * 24 * 60 * 60 * 1000 // Timestamp of 3 days ago | |
storage.getAllKeys().forEach((entry) => { | |
// we only want to clear the data for react-query with the prefix 'my-random-prefix' | |
if (!entry.startsWith('my-random-prefix')) { | |
return | |
} | |
const rawValue = storage.getString(entry) | |
if (!rawValue) return | |
try { | |
const value = JSON.parse(rawValue) | |
if (value?.state?.dataUpdatedAt && value.state.dataUpdatedAt < threeDaysAgo) { | |
storage.delete(entry) | |
} | |
} catch (error) { | |
console.error(`Error parsing JSON for key ${entry}:`, error) | |
} | |
}) | |
}, []) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
And a more sophisticated solution: