Skip to content

Commit

Permalink
(DOCSP-28276) Add argument to useQuery to allow result to be filter…
Browse files Browse the repository at this point in the history
…ed and sorted (#3063)

## Pull Request Info

This PR updates the syntax for `useQuery()` when it's used with
`.filtered()` and `.sorted()`. Essentially, going from this:
```JS
const contactsInArea = contacts.filtered(`address.postalCode == '${postalCode}'`);
```
to this:
```JS
const contactsInArea = useQuery(
  Contact,
  contacts => {
    return contacts.filtered(`address.postalCode == '${postalCode}'`);
  },
  [postalCode],
);
```

The new syntax has baked-in performance improvements and is the
recommended way to handle filtering and sorted. We should avoid
`useQuery(<ObjectClass>).sorted()` or
`useQuery(<ObjectClass>).filtered()`.

### Jira

- https://jira.mongodb.org/browse/DOCSP-28276

### Staged Changes

- [Code samples throughout the React Native SDK
docs](https://preview-mongodbkrollinsmdb.gatsbyjs.io/realm/DOCSP-28276/sdk/react-native/)

### Review Guidelines


[REVIEWING.md](https://github.com/mongodb/docs-realm/blob/master/REVIEWING.md)

### Animal Wearing a Hat

<img
src="https://images.unsplash.com/photo-1575425187336-d5ec5d0a1451?auto=format&fit=crop&q=80&w=1000&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxzZWFyY2h8N3x8ZG9nJTIwaGF0fGVufDB8fDB8fHww"
width=400>
  • Loading branch information
krollins-mdb authored Nov 1, 2023
1 parent 4b0f02f commit 4cc6ba7
Show file tree
Hide file tree
Showing 66 changed files with 709 additions and 407 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,9 @@ describe('Delete Data Tests', () => {
const myDogs = useQuery(Dog);

const deleteAllYoungDogObjects = () => {
const youngDogs = myDogs.filtered('age < 3');
const youngDogs = useQuery(Dog, dogs => {
return dogs.filtered('age < 3');
});
realm.write(() => {
realm.delete(youngDogs);
});
Expand Down
41 changes: 25 additions & 16 deletions examples/react-native/legacy/__tests__/js/CRUD/read.test.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -114,18 +114,19 @@ describe('Read Data Tests', () => {
// }
// }
const TaskList = () => {
// retrieve the set of Task objects
const tasks = useQuery(Task);

// filter for tasks with a high priority
const highPriorityTasks = tasks.filtered('priority >= $0', 4);
const highPriorityTasks = useQuery(Task, tasks => {
return tasks.filtered('priority >= $0', 4);
});

// filter for tasks that have just-started or short-running progress
const lowProgressTasks = tasks.filtered(
'$0 <= progressMinutes && progressMinutes < $1',
1,
10,
);
const lowProgressTasks = useQuery(Task, tasks => {
return tasks.filtered(
'$0 <= progressMinutes && progressMinutes < $1',
1,
10,
);
});

return (
<>
Expand Down Expand Up @@ -190,16 +191,24 @@ describe('Read Data Tests', () => {
// retrieve the set of Task objects
const tasks = useQuery(Task);
// Sort tasks by name in ascending order
const tasksByName = tasks.sorted('name');
const tasksByName = useQuery(Task, tasks => {
return tasks.sorted('name');
});
// Sort tasks by name in descending order
const tasksByNameDescending = tasks.sorted('name', true);
const tasksByNameDescending = useQuery(Task, tasks => {
return tasks.sorted('name', true);
});
// Sort tasks by priority in descending order and then by name alphabetically
const tasksByPriorityDescendingAndName = tasks.sorted([
['priority', true],
['name', false],
]);
const tasksByPriorityDescendingAndName = useQuery(Task, tasks => {
return tasks.sorted([
['priority', true],
['name', false],
]);
});
// Sort Tasks by Assignee's name.
const tasksByAssigneeName = tasks.sorted('assignee.name');
const tasksByAssigneeName = useQuery(Task, tasks => {
return tasks.sorted('assignee.name');
});

return (
<>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,14 +45,26 @@ const FindSortFilterComponent = ({objectPrimaryKey}) => {
const profiles = useQuery(Profile);

const sortProfiles = reversed => {
const sorted = profiles.sorted('name', reversed);
const sorted = useQuery(
Profile,
profiles => {
return profiles.sorted('name', reversed);
},
[reversed],
);

setAllProfiles(sorted);
};

const filterProfiles = (filter, letter) => {
// Use [c] for case-insensitivity.
const filtered = profiles.filtered(`name ${filter}[c] "${letter}"`);
const filtered = useQuery(
Profile,
profiles => {
return profiles.filtered(`name ${filter}[c] "${letter}"`);
},
[filter, letter],
);

setAllProfiles(filtered);
// For testing only. Ensures filtering works. // :remove:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -60,17 +60,22 @@ describe('Dictionary Tests', () => {

// run the `.filtered()` method on all the returned homeOwners to
// find all homeOwners that have a house with a listed price
const listedPriceHomes = homeOwners.filtered('home.@keys = "price"');
const listedPriceHomes = useQuer(HomeOwner, homeOwners => {
return homeOwners.filtered('home.@keys = "price"');
});

// run the `.filtered()` method on all the returned homeOwners to
// find the house with the address "Summerhill St."
const summerHillHouse = homeOwners.filtered(
'home["address"] = "Summerhill St."',
)[0].home;
const summerHillHouse = useQuery(HomeOwner, homeOwners => {
return homeOwners.filtered('home["address"] = "Summerhill St."');
})[0].home;

// run the `.filtered()` method on all the returned homeOwners to
// find the first house that has any field with a value of 'red'
const redHouse = homeOwners.filtered('home.@values = "red"')[0].home;
const redHouse = useQuery(HomeOwner, homeOwners => {
return homeOwners.filtered('home.@values = "red"');
})[0].home;

return (
<View>
<Text>All homes:</Text>
Expand Down Expand Up @@ -140,8 +145,12 @@ describe('Dictionary Tests', () => {
const UpdateHome = ({homeOwnerName}) => {
const [address, setAddress] = useState('3 jefferson lane');
const realm = useRealm();
const homeOwner = useQuery(HomeOwner).filtered(
`name == '${homeOwnerName}'`,
const homeOwner = useQuery(
HomeOwner,
homeOwners => {
return homeOwners.filtered(`name == '${homeOwnerName}'`);
},
[homeOwnerName],
)[0];

const updateAddress = () => {
Expand Down Expand Up @@ -206,8 +215,12 @@ describe('Dictionary Tests', () => {
// }
const HomeInfo = ({homeOwnerName}) => {
const realm = useRealm();
const homeOwner = useQuery(HomeOwner).filtered(
`name == '${homeOwnerName}'`,
const homeOwner = useQuery(
HomeOwner,
homeOwners => {
return homeOwners.filtered(`name == '${homeOwnerName}'`);
},
[homeOwnerName],
)[0];

const deleteExtraHomeInfo = () => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -159,13 +159,14 @@ describe('embedded objects tests', () => {
// }
// }
const ContactList = ({postalCode}) => {
// Query for all Contact objects
const contacts = useQuery(Contact);

// Run the `.filtered()` method on all the returned Contacts to get
// contacts with a specific postal code.
const contactsInArea = contacts.filtered(
`address.postalCode == '${postalCode}'`,
const contactsInArea = useQuery(
Contact,
contacts => {
return contacts.filtered(`address.postalCode == '${postalCode}'`);
},
[postalCode],
);
higherScopedContactsInArea = contactsInArea; // :remove:

Expand Down Expand Up @@ -210,14 +211,21 @@ describe('embedded objects tests', () => {
// }
// }
const ContactInfo = ({contactCity, postalCode}) => {
const contacts = useQuery(Contact);
const parentsToDelete = contacts.filtered(
`address.city == '${contactCity}'`,
const realm = useRealm();
const parentsToDelete = useQuery(
Contact,
contacts => {
return contacts.filtered(`address.city == '${contactCity}'`);
},
[contactCity],
);
const embeddedToDelete = contacts.filtered(
`address.postalCode == '${postalCode}'`,
const embeddedToDelete = useQuery(
Contact,
contacts => {
return contacts.filtered(`address.postalCode == '${postalCode}'`);
},
[postalCode],
);
const realm = useRealm();

const deleteParentObject = () => {
realm.write(() => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,13 @@ describe('Mixed Tests', () => {
const CatInfoCard = ({catName}) => {
// To query for the cat's birthDate, filter for their name to retrieve the realm object.
// Use dot notation to access the birthDate property.
const cat = useQuery(Cat).filtered(`name = '${catName}'`)[0];
const cat = useQuery(
Cat,
cats => {
return cats.filtered(`name = '${catName}'`);
},
[catName],
)[0];
const catBirthDate = cat.birthDate;

if (cat) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -135,14 +135,13 @@ describe('relationships tests', () => {
// }
// }
const PostsByYoungUsers = () => {
const posts = useQuery(Post);
const postsByYoungUsers = useMemo(() => {
const postsByYoungUsers = useQuery(Post, posts => {
return posts.filtered(
'@links.User.posts.birthdate >= 2000-01-01@00:00:00:0',
);
}, [posts]);
});

if (!posts) return <Text>The post was not found.</Text>;
if (!postsByYoungUsers) return <Text>The post was not found.</Text>;
return (
<View>
<Text>Posts By Young Users</Text>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -108,8 +108,12 @@ describe('Set schema', () => {
const AddInventoryToCharacter = ({characterName}) => {
const realm = useRealm();
const [inventoryItem, setInventoryItem] = useState('');
const character = useQuery(Character).filtered(
`name = '${characterName}'`,
const character = useQuery(
Character,
characters => {
return characters.filtered(`name = '${characterName}'`);
},
[characterName],
)[0];

const addInventoryItem = () => {
Expand Down Expand Up @@ -170,8 +174,12 @@ describe('Set schema', () => {
// }
const QueryCharacterInventory = ({characterName}) => {
const [inventoryItem, setInventoryItem] = useState('');
const character = useQuery(Character).filtered(
`name = '${characterName}'`,
const character = useQuery(
Character,
characters => {
return characters.filtered(`name = '${characterName}'`);
},
[characterName],
)[0];

const queryCharacterInventory = () => {
Expand Down Expand Up @@ -247,8 +255,12 @@ describe('Set schema', () => {
const RemoveInventoryFromCharacter = ({characterName}) => {
const realm = useRealm();
const [inventoryItem, setInventoryItem] = useState('');
const character = useQuery(Character).filtered(
`name = '${characterName}'`,
const character = useQuery(
Character,
characters => {
return characters.filtered(`name = '${characterName}'`);
},
[characterName],
)[0];

const removeInventoryItem = () => {
Expand Down Expand Up @@ -336,8 +348,12 @@ describe('Set schema', () => {
const [inventoryItem, setInventoryItem] = useState('');
const [inventory, setInventory] = useState([]);

const character = useQuery(Character).filtered(
`name = '${characterName}'`,
const character = useQuery(
Character,
characters => {
return characters.filtered(`name = '${characterName}'`);
},
[characterName],
)[0];

const addInventoryItem = () => {
Expand Down
11 changes: 7 additions & 4 deletions examples/react-native/legacy/__tests__/ts/CRUD/delete.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,9 @@ describe('Delete Data Tests', () => {

fireEvent.press(firstDeleteDogButton);

await waitFor(() => {expect(getAllByTestId('deleteDog').length).toBe(2)});
await waitFor(() => {
expect(getAllByTestId('deleteDog').length).toBe(2);
});

expect(assertionRealm.objects('Dog').length).toBe(2);
expect(getAllByTestId('deleteDog').length).toBe(2);
Expand All @@ -99,7 +101,9 @@ describe('Delete Data Tests', () => {
const myDogs = useQuery(Dog);

const deleteAllYoungDogObjects = () => {
const youngDogs = myDogs.filtered('age < 3');
const youngDogs = useQuery(Dog, dogs => {
return dogs.filtered('age < 3');
});
realm.write(() => {
realm.delete(youngDogs);
});
Expand Down Expand Up @@ -167,7 +171,6 @@ describe('Delete Data Tests', () => {
});

expect(assertionRealm.objects('Dog').length).toBe(0);

});

it('should delete all objects', async () => {
Expand Down Expand Up @@ -207,7 +210,7 @@ describe('Delete Data Tests', () => {
await act(async () => {
fireEvent.press(deleteAllDataBtn);
});

expect(assertionRealm.objects('Dog').length).toBe(0);
expect(assertionRealm.objects('Person').length).toBe(0);
});
Expand Down
Loading

0 comments on commit 4cc6ba7

Please sign in to comment.