Search code examples
javascriptreact-nativerealm

Storing arrays in react-native realm


I cant seem to store an array from a json to my realm database. Lets say the json that was returned to me is:

  contact: 
      { 
          name: 'Test Name',
          contactDetails: [ '4354354', '099324' ] 
      },

How can I insert contactDetails into realm?

Ive tried creating a custom object like this according to this How to store [String] or [Int] in react-native realm:

class stringObject extends Realm.Object {}
    stringObject.schema = {
     name: 'stringObject',
      properties: { value : 'string' }
     };

And tried adding this to the schema:

  contactDetails: {type: 'list', objectType: 'stringObject'}

But it cant be inserted into realm. I tried emptying the value in properties for my stringObject but it still doesnt work.


Solution

  • Lists in Realm contain objects so you need to transform you JSON to the correct form before insertion. For the schema you provided you need to transform contactDetails to represent an array of valid StringObject objects before calling realm.create:

    contactDetails: [ '4354354', '099324' ] 
    

    to

    contactDetails: [ { value: '4354354' }, { value: '099324' } ] 
    

    You could do this using Array.map with something like:

    json.contactDetails = json.contactDetails.map( s => ({ value: s }) );