-
-
Save onetrace-abdullah/46f2a736219cbb216e2c8109303afb0e to your computer and use it in GitHub Desktop.
Realm sync demo
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Author
onetrace-abdullah
commented
Jun 20, 2023
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment