Error: Cannot create asynchronous query while in a write transaction

I’m developing a chat app and using Realm as a local database to store messages and other data. I’m using the singleton realm provider pattern as outlined by Andrew Meyer in this meetup (Realm Meetup - Realm JavaScript for React Native applications - YouTube). When a user sends a message, the app receives the data via a websocket or other means (i.e. push notification) and writes it to the database. The idea is that if a message is written to the database and a user is viewing that particular list of messages, it should appear in the list, which it does. However, I’m occasionally seeing the error: “Error: Cannot create asynchronous query while in a write transaction”. I have researched this and I believe that it’s saying that while the database is being written to, a component can’t create a listener. Seems like some kind of race condition or something where the message is being written to the database while components (some with listeners) are being rendered.

Is this accurate? If so, what pattern should I be using to avoid this error?

Thanks!

That would indeed be a race condition but generally speaking that would not happen.

What’s the use case where you’re creating a listener within a write transaction?

Do you have some example code that shows what’s being done that is causing this issue?

Thanks for the follow up. I answered my own question I believe. I had a misunderstanding of Realm’s capabilities. Since Realm objects are “live” objects and auto-update based on the query, the listeners I was adding aren’t necessary. I just needed to understand conceptually that Realm objects are live so I can basically do something like:

const [myList, setMyList] = React.useState<Realm.Results<MyObject & Realm.Object>>();

setMyList(realm.objects(“MY_OBJECT_SCHEMA”).filtered(objectGroupId == '${groupId}'));

see: https://docs.mongodb.com/realm/sdk/react-native/fundamentals/live-queries/

Then at this point, if I have a FlatList or myList.map(…) or whatever, React will automatically re-render if the results of the query stored in my react state change.

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.