Dictionaries - React Native SDK
On this page
New in version realm@10.5.0
.
You can use the Realm.Dictionary data type to
manage a collection of unique String keys paired with values. The dictionary
data maps to the Javascript Object type.
For example, creating a HomeOwner
Realm object where the home
property
is defined as a dictionary
type could look like this:
realm.create('HomeOwner', { name: 'Anna Smith', home: {address: '2 jefferson lane', yearRenovated: 1994, color: 'blue'}, });
Realm Object Models
You can define a dictionary of mixed values for a Realm object model in three ways:
set the data type of your field to an empty object,
"{}"
.Add the data type before the brackets to create a dictionary with values of a specific type. For example,
"int{}"
to specify that dictionary values must be integers or"string{}"
to specify that dictionary values must be strings.Define the object type explicitly. This is necessary for using object Types in your Realm as ditionary values.
Realm disallows the use of .
or $
characters in map keys.
You can use percent encoding and decoding to store a map key that contains
one of these disallowed characters.
// Percent encode . or $ characters to use them in map keys const mapKey = "kitchen.windows"; const encodedMapKey = mapKey.replace(".", "%2E");
Create an Object with a Dictionary Value
In the following CreateHomeOwner
example, we create a new object with a dictionary property.
The CreateHomeOwner
component does the following:
Create React state that represents the homeowner's name and address, respectively.
Get access to an open realm instance by calling the
useRealm()
hook within the component.Create a component method
SubmitHomeOwner()
that performs a write transaction and creates a newHomeOwner
object based on theTextInput
values for the homeowner's name and address, respectively.Add an onPress event on the submit button that calls
SubmitHomeOwner()
1 const CreateHomeOwner = () => { 2 const [homeOwnerName, setHomeOwnerName] = useState('John Smith'); 3 const [address, setAddress] = useState('1 Home Street'); 4 const realm = useRealm(); 5 6 const submitHomeOwner = () => { 7 // Create a HomeOwner realm object within a Write Transaction 8 realm.write(() => { 9 realm.create('HomeOwner', { 10 name: homeOwnerName, 11 // For the dictionary field, 'home', set the value 12 // to a regular JavaScript object 13 home: { 14 address, 15 }, 16 }); 17 }); 18 }; 19 return ( 20 <View> 21 <TextInput 22 value={homeOwnerName} 23 onChangeText={text => setHomeOwnerName(text)} 24 /> 25 <TextInput value={address} onChangeText={text => setAddress(text)} /> 26 <Button 27 title='Submit Home Owner' 28 onPress={submitHomeOwner} 29 /> 30 </View> 31 ); 32 };
Query for Objects with a Dictionary Property
To filter a query, run collection.filtered() to specify a subset of results based on the value(s) of one or more object properties. You can specify results based on the value of a dictionary's properties by using bracket notation.
You can also determine whether a results collection has a certain key or value
by using <dictionary>.@keys
or <dictionary>.@values
. For instance, if
you had a HomeOwner
collection with a nested home
dictionary, you could
return all HomeOwner
objects with a home
with a "price"
property by
running the query: home.@keys = "price"
.
Example
In the following HomeList
example, we query for objects that have dictionary properties.
The HomeList
component does the following:
Performs a query for all homeowners by passing the
HomeOwner
class to theuseQuery
hook.Performs a query for homeowners with a listed price by passing
collection.filtered()
the query:home.@keys = "price"
.Performs a query for the summer hill house by running
collection.filtered()
using bracket notation to find the first homeowner with an address set to "Summerhill St." and getting their home by using dot syntax.Performs a query for all homeowners with any field with a value of red by passing
collection.filtered()
the query:'home.@values = "red"'
. We then get the first homeowner's home.Display the results of our queries in the UI by rendering information about the homes
Update a Dictionary
Update a dictionary's property by using the dictionary.set() method or dot notation to set its property to a new value.
Example
In the following UpdateHome
example, we update a dictionary's property.
The UpdateHome
component does the following:
- Create a React state
- variable that represents the home address.
- Get access to an opened realm instance by calling the
useRealm()
hook - within the component.
- Get access to an opened realm instance by calling the
- Create a component method
updateAddress()
that performs a write - transaction and uses
dictionary.set()
to set the home's address to the value of theaddress
state variable. It also uses dot syntax to set theyearRenovated
to2004
.
- Create a component method
Render a
TextInput
that displays and changes theaddress
state variable.- Add an onPress event on
- the "Update Address" button that calls
updateAddress()
Delete Members of a Dictionary
To delete members of a dictionary, use the dictionary.remove() method with an array of properties to remove from the dictionary.
Example
In the following HomeInfo
example, we delete members of a dictionary.
The HomeInfo
component does the following:
Get access to an open realm instance by calling the
useRealm()
hook within the component.Retrieve the first homeowner that matches the name passed into the component as a prop. We do this by getting the first value returned from the query:
useQuery(HomeOwner).filtered(`name == '${homeOwnerName}'`)
.Create a component method
deleteExtraHomeInfo()
that performs a write transaction and callsdictionary.remove()
to remove theyearRenovated
andcolor
properties.Render the homeowner's name and home address in the UI.
Add an onPress event on the "Delete extra home info" button that calls
deleteExtraHomeInfo()
.