flexbox / react-native-bootcamp

1 week, 20+ lessons, opinionated React Native Bootcamp for busy developers.
https://davidl.fr/bootcamp
212 stars 12 forks source link

migrate Offline challenge to offline first with React Query #227

Open flexbox opened 2 months ago

flexbox commented 2 months ago

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


References:

hirbod commented 2 months ago

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.

Bildschirmfoto 2024-03-07 um 15 10 46
hirbod commented 2 months ago

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

hirbod commented 2 months ago

Here is my stale data remover https://gist.github.com/hirbod/bc1538990d1b47419c3cb1f6622f7625

flexbox commented 2 months ago

@hirbod thanks! so @MatthysDev owns you a drink at the next Appjs!