Skip to content

Instantly share code, notes, and snippets.

@onetrace-abdullah
Created June 20, 2023 14:20
Show Gist options
  • Save onetrace-abdullah/46f2a736219cbb216e2c8109303afb0e to your computer and use it in GitHub Desktop.
Save onetrace-abdullah/46f2a736219cbb216e2c8109303afb0e to your computer and use it in GitHub Desktop.
Realm sync demo
import { ActivityIndicator, Button, SafeAreaView, ScrollView, Text, View } from 'react-native'
import { useEffect, useMemo, useState } from 'react'
export type Item = {
_id: Realm.BSON.ObjectId
company_id: number
text: string
}
export const ItemSchema = {
name: 'Item',
properties: {
_id: { type: 'objectId' },
company_id: { type: 'int' },
text: { type: 'string' },
},
primaryKey: '_id',
}
const App = () => {
const [count, setCount] = useState(0)
const [loading, setLoading] = useState(true)
const [realm, setRealm] = useState<Realm | null>(null)
const app = useMemo(() => new Realm.App({ id: 'application-0-kqehi' }), [])
const refresh = () => setCount(count + 1)
useEffect(() => {
app.logIn(Realm.Credentials.anonymous()).then((user) => {
const $realm = new Realm({
schema: [ItemSchema],
sync: {
flexible: true,
user,
newRealmFileBehavior: { type: 'openImmediately' as Realm.OpenRealmBehaviorType },
existingRealmFileBehavior: { type: 'openImmediately' as Realm.OpenRealmBehaviorType },
},
})
$realm.subscriptions
.update((mutableSubs) => {
mutableSubs.add($realm.objects(ItemSchema.name))
})
.then(() => {
setRealm($realm)
refresh()
setLoading(false)
})
})
}, [])
const items = useMemo(() => (realm ? (realm.objects(ItemSchema.name) as Realm.Results<Readonly<Item>>) : []), [count])
if (loading || !realm) {
return (
<SafeAreaView>
<ActivityIndicator />
</SafeAreaView>
)
}
const companyIds = [1, 2, 3]
const create = () => {
realm.write(() => {
realm.create<Item>(ItemSchema.name, {
_id: new Realm.BSON.ObjectID(),
company_id: companyIds[Math.floor(Math.random() * companyIds.length)],
text: Math.random().toString(36).replace('0.', ''),
})
})
refresh()
}
return (
<SafeAreaView>
<Button title='Refresh' onPress={refresh} />
<Button title='Create' onPress={create} />
<ScrollView contentContainerStyle={{ gap: 8 }}>
{items.map((test) => (
<View
key={String(test._id)}
style={{ backgroundColor: '#CCC', borderWidth: 2, borderColor: '#BBB', borderRadius: 20, padding: 20 }}
>
<Text>{JSON.stringify(test)}</Text>
</View>
))}
</ScrollView>
</SafeAreaView>
)
}
export default App
@onetrace-abdullah
Copy link
Author

simulator_screenshot_1155F9E4-524C-4EC2-B894-F93D9070C02F

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment