RFC: change `experimental_createPersister`'s `serialize`/`deserialize` types #6441
Send to my agentDescribe the bug#
The great @TheTimeWalker proposed here to avoid using serialization/deserialization using IndexedDB:
One suggestion: The advantage of IndexedDB is that you can safely put objects into the storage without having to rely on serializing/deserializing the content like e.g. with LocalStorage. I have noticed that right now it would by default still stringify the content and then save it to IndexedDB. My suggestion would be to additionally add this into your persister:
experimental_createPersister({
// ...
// Just pass the data
serialize: (persistedQuery) => persistedQuery,
deserialize: (cached) => cached,
})
The only problem is that TypeScript will complain that this serialize/deserialize function is not assignable, because it expects a string as a return type and cached type.
Specifically this:
Type '(persistedQuery: PersistedQuery) => PersistedQuery' is not assignable to type '(persistedQuery: PersistedQuery) => string'.
Type 'PersistedQuery' is not assignable to type 'string'.ts(2322)
Type '(cached: string) => string' is not assignable to type '(cachedString: string) => PersistedQuery'.
Type 'string' is not assignable to type 'PersistedQuery'.ts(2322)
Here's the Typescript Playground
Because the IndexedDB storage is used which means that it doesn't make much sense to return a string. If you serialize to string then the DB will only contain one entry which is just a stringified and escaped JSON object. After all, that's what's said as an advantage in the persistQueryClient doc where you don't need to serialize the result :)
Unfortunately, the only way I see is to set the serializer and deserializer to just pass the object overwriting the JSON.stringify function as I can't just disable the serializer and natively pass the object to the database.
I'm opening this issue to fix the type issue here.
TkDodo added labelsenhancement
TkDodo added labelspackage: query-persist-client-core
@frederikhors Try with https://github.com/TanStack/query/releases/tag/v5.10.0
@DamianOsipiuk I'll try in a few hours...
Works! Thanks for the solution! 🎉
I've added a revised example code with the new typing feature under the original discussion: https://github.com/TanStack/query/discussions/6213#discussioncomment-7715299
But to mention quickly what I did: Under AsyncStorage and createrPersister, just add
<PersistedQuery>. This makes TypeScript happy and everything is typed correctly@DamianOsipiuk it works amazingly! THANK YOU!
Sign in to join this conversation.
@DamianOsipiuk FYI