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"
2
Answers
I’m having the same issue here, ignore that chump above.
Strangely – if you use locations.map() you’ll be able to render using the same data set, but FlatList returns an empty UI.
If you use the underlying VirtualizedList component and pass data={locations} you’ll also be able to render.
There must be something with the FlatList component itself that’s having issues with the realm results from useQuery.
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.