Uploaded image for project: 'Realm JavaScript SDK'
  1. Realm JavaScript SDK
  2. RJS-2897

Flatlist accessing object of type X which has been invalidated or deleted

      How frequently does the bug occur?

      Sometimes

      Description

      We have switched to @realm/react and we are running into intermittent crashes. The issues are very similar to #1031. We are getting an Accessing object of type X which has been invalidated or deleted error. This is a pseudo-code of what we are doing.

      const items = useQuery(List)
      
      useEffect(() => {
         async function fetchData() {
            // fetch the List from the server and update
         }
         fetchData()
      }, [])
      
      return <Flatlist data={items} renderItem={renderItem} />
      

      I want to mention that List has an embedded Realm object as well. The crash tends to happen when we are rendering a large number of items and scrolling at the same time while we are fetching the list from the server.

      Judging by the error, we are accessing old Realm objects within the renderItem function which was quite surprising since we are using @realm/react and expected it to take care of this kind of issue.

      I noted this from the React Native docs.

      > In order to constrain memory and enable smooth scrolling, content is rendered asynchronously offscreen. This means it's possible to scroll faster than the fill rate and momentarily see blank content.

      I think the asynchronous rendering of the Flatlist is the culprit. This is what I think is happening but I might be wrong.

      1. The initial data is rendered.
      2. Flatlist is deferring the rendering of items not visible on the screen.
      3. fetchData is called and the Realm is updated.
      4. The user scrolls the list causing Flatlist to access the invalidated object.
      5. useQuery schedules a rerender(the app will crash by the time this happens).

      Are you guys aware of these issues? Is there any recommendation on how to use Realm with Flatlist?

      For the time being, we are using isValid to check within the renderItem prop before accessing the Realm object but this doesn't look right.

      Stacktrace & log output

      No response

      Can you reproduce the bug?

      Sometimes

      Reproduction Steps

      No response

      Version

      realm: 12.6.0, @realm/react: 0.6.2

      What services are you using?

      Local Database only

      Are you using encryption?

      Yes

      Platform OS and version(s)

      Android 14

      Build environment

      React Native: 0.73.6
      New Architecture: false
      Engine: Hermes

      Cocoapods version

      No response

            Assignee:
            Unassigned Unassigned
            Reporter:
            unitosyncbot Unito Sync Bot
            Votes:
            0 Vote for this issue
            Watchers:
            2 Start watching this issue

              Created:
              Updated: