Skip to content

Commit

Permalink
Nullable embedded field (realm 12.3.1)
Browse files Browse the repository at this point in the history
  • Loading branch information
andreyukD committed Nov 24, 2023
1 parent 33777db commit 8270070
Show file tree
Hide file tree
Showing 4 changed files with 26 additions and 9 deletions.
8 changes: 4 additions & 4 deletions app/components/TaskItem.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import React from 'react';
import Realm from 'realm';
import {View, Text, Pressable, StyleSheet} from 'react-native';
import {View, Text, Pressable, StyleSheet, TouchableOpacity} from 'react-native';

import {shadows} from '../styles/shadows';
import colors from '../styles/colors';
Expand Down Expand Up @@ -33,9 +33,9 @@ export const TaskItem = React.memo<TaskItemProps>(
</Pressable>
</View>
<View>
<Pressable onPress={onAddSubItems}>
<Text style={styles.edit}>Edit first item</Text>
</Pressable>
<TouchableOpacity onPress={onAddSubItems}>
<Text style={styles.edit}>{`Toggle address (object <-> null)`}</Text>
</TouchableOpacity>
<Text style={styles.subItems}>SubItems: {JSON.stringify(task.items)}</Text>
</View>
</>
Expand Down
9 changes: 7 additions & 2 deletions app/components/TaskManager.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -69,8 +69,13 @@ export const TaskManager: React.FC<{

const handleAddSubItems = useCallback((task: Task & Realm.Object): void => {
realm.write(() => {
// different behaviour on Realm 12, it pushes new item instead of updating one
task.items[0] = {name: 'First item changed'}
// different behaviour on Realm 12, it doesn't allow setting null for embedded schema field,
// but it can be null on init app
const firstItem = task.items[0]
firstItem['address'] = !firstItem.address ? {
city: 'Warsaw',
country: 'PL'
} : null
});
}, [realm])

Expand Down
14 changes: 13 additions & 1 deletion app/models/Task.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,19 @@ export class ItemSchema extends Realm.Object {
name: 'ItemSchema',
embedded: true,
properties: {
name: 'string'
name: 'string',
address: 'AddressSchema'
},
};
}

export class AddressSchema extends Realm.Object {
static schema: Realm.ObjectSchema = {
name: 'AddressSchema',
embedded: true,
properties: {
city: 'string',
country: 'string'
},
};
}
4 changes: 2 additions & 2 deletions app/models/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
import {ItemSchema, Task} from './Task';
import {AddressSchema, ItemSchema, Task} from './Task';

export const schemas = [Task, ItemSchema];
export const schemas = [Task, ItemSchema, AddressSchema];

0 comments on commit 8270070

Please sign in to comment.