migrate Offline challenge to offline first with React Query
flexbox opened this issue · 4 comments
Thanks to @hirbod i randomly landed on this tweet.
we should use tanstack-query with query-async-storage-persister
as a dev,
I can improve my knowledge of offline first app,
so that I can use @tanstack/query-async-storage-persister
- Update
StarshipCard>handleBuyto return<Text>payment in process</Text> - Udpate data-02 challenge to use only
Netinfo - Create a new data-03 challenge with the instruction for
query-async-storage-persister - for the api endpoint we could use a service like https://mockaroo.com/ to store the
StarshipCarddata
References:
Let me give you the whole thing. And you have to use the experimental one, because this is what we need for RN.
import { MMKV } from 'react-native-mmkv'
import { experimental_createPersister } from '@tanstack/react-query-persist-client'
import Constants from 'expo-constants'
import * as Updates from 'expo-updates'
export const storage = new MMKV({
id: 'yourawesomekey',
})
type ClientStorage = {
setItem: typeof storage.set
getItem: (key: string) => string | null
removeItem: typeof storage.delete
}
export const ReactQueryMMKVPersisterStorage: ClientStorage = {
setItem: (key, value) => {
storage.set(key, value)
},
getItem: (key) => {
const value = storage.getString(key)
return value === undefined ? null : value
},
removeItem: (key) => {
storage.delete(key)
},
}
export const persister = experimental_createPersister({
maxAge: 1000 * 60 * 60 * 12, // 12 hours
storage: ReactQueryMMKVPersisterStorage,
prefix: 'my-awesome-key',
buster: `${Constants.manifest2?.runtimeVersion}_${Updates.updateId}`,
})Then you just pass it globally to the queryClient defaults as persister and you also need to pass it individually for every infiniteQuery, as the global setting does not work for infiniteQueries. Types also broken, but it works.

One thing to mention: the experimental persister only detects and deletes old cache entries when the keys are accessed . This can lead to a lot of stale persisted data. I haven't finished it yet, but I am planning to add a tiny storage lookup on boot and remove data that is older than (3)/n days or something like that.
The issue is known and reported by me but unsolved for now
Here is my stale data remover https://gist.github.com/hirbod/bc1538990d1b47419c3cb1f6622f7625
@hirbod thanks!
so @MatthysDev owns you a drink at the next Appjs!