Search code examples
react-nativerealm

Why does my list of Realm objects loaded into FlatList using realm-react only render if I use the spread operator?


import React from "react"
import { initialWindowMetrics, SafeAreaProvider } from "react-native-safe-area-context"
import {FlatList, SafeAreaView, Text, View, } from "react-native";
import {colors} from "./theme";
import {LocationRealm} from "./realm/models/LocationRealm";
import RealmContext from './realm/AppRealm';

const { RealmProvider, useQuery } = RealmContext;

function App() {
    return <RealmProvider>
        <SafeAreaProvider initialMetrics={initialWindowMetrics}>
            <LocationsView/>
        </SafeAreaProvider>
    </RealmProvider>
}

export const LocationsView = () => {

    const locations = useQuery(LocationRealm)

    return (
        <SafeAreaView style={{flex: 1, height: "100%"}}>
            <FlatList
                data={[...locations]} // <--- working (shows on UI)
                // data={locations} // <-- not working (empty list)
                keyExtractor={ (item, index) => `${item.id}` }
                renderItem={({item}) => {
                    {console.log(item)}
                    return <View style={{height: 100, backgroundColor: colors.tint}}>
                        <Text>{item.locationName}</Text>
                    </View>
                }}
            />
        </SafeAreaView>
    )
}

export default App

import Realm from "realm";

export class LocationRealm extends Realm.Object<LocationRealm> {

    id!: string;
    locationName!: string;

    static generate(index: number, name: String) {
        return {
            id: `${Math.random()}`,
            locationName: name,
        }
    }

    static schema: Realm.ObjectSchema = {
        name: "LocationRealm",
        primaryKey: "id",
        properties: {
            id: "string",
            locationName: "string",
        }
    }

}

The above code is only rendering LocationRealm objects into the UI from the Realm Database when using [...locations] instead of just locations. In all the demos and example projects I have seen, the spread operator was not needed. I am not getting any error messages or crashes, just an empty FlatList.

"@realm/react": "^0.4.3"

"realm": "^11.4.0"

Solution

  • https://github.com/realm/realm-js/issues/5404

    The issue is that FlatList from react-native introduced a guard in the _getItemCount function in RN 0.71.2. Here is the commit:

    https://github.com/facebook/react-native/commit/d574ea3526e713eae2c6e20c7a68fa66ff4ad7d2

    useQuery returns an object of type Realm.Results, which fails the Array.isArray() guard.

    You can use patch-package to remove the guard from the FlatList.