Skip to content

Commit

Permalink
Fix types for Object Listener (#4338)
Browse files Browse the repository at this point in the history
When a class extends Realm.Object, adding a listener to an instance of the
object would not correctly type the object returned in the callback.
With this change, the callback returns an object of the same type as the
instance it was called from.
  • Loading branch information
takameyer authored Feb 14, 2022
1 parent df06e97 commit 905b1fc
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 9 deletions.
1 change: 1 addition & 0 deletions .gitignore-revs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
c76131748cbb048e78a987eb234d8a9609e26430
f38d8cf7cac992767a451d2f3cf3310e3546bf6f
fa80f12bf3fbfe1337ae69e12c59051fac347001
99e64a8e990d2579bcfe382f755edbc61f70af4e
12 changes: 9 additions & 3 deletions packages/realm-react/src/useObject.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -28,15 +28,21 @@ export function createUseObject(useRealm: () => Realm) {
);

useEffect(() => {
const listenerCallback: Realm.ObjectChangeCallback = (_, changes) => {
const listenerCallback: Realm.ObjectChangeCallback<T & Realm.Object> = (_, changes) => {
if (changes.changedProperties.length > 0) {
setObject(() => realm.objectForPrimaryKey(type, primaryKey) ?? null);
} else if (changes.deleted) {
setObject(null);
}
};
object?.addListener(listenerCallback);
return () => object?.removeListener(listenerCallback);
if (object !== null) {
object.addListener(listenerCallback);
}
return () => {
if (object !== null) {
object.removeListener(listenerCallback);
}
};
}, [realm, object, type, primaryKey]);

return object;
Expand Down
12 changes: 6 additions & 6 deletions types/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -199,12 +199,12 @@ declare namespace Realm {
[keys: string]: any;
}

interface ObjectChangeSet {
interface ObjectChangeSet<T> {
deleted: boolean;
changedProperties: string[]
changedProperties: (keyof T)[]
}

type ObjectChangeCallback = (object: Object, changes: ObjectChangeSet) => void;
type ObjectChangeCallback<T> = (object: T, changes: ObjectChangeSet<T>) => void;

/**
* Object
Expand Down Expand Up @@ -251,16 +251,16 @@ declare namespace Realm {
/**
* @returns void
*/
addListener(callback: ObjectChangeCallback): void;
addListener(callback: ObjectChangeCallback<this>): void;

removeListener(callback: ObjectChangeCallback): void;
removeListener(callback: ObjectChangeCallback<this>): void;

removeAllListeners(): void;

/**
* @returns string
*/
getPropertyType(propertyName: string) : string;
getPropertyType(propertyName: string): string;
}

/**
Expand Down

0 comments on commit 905b1fc

Please sign in to comment.