Sync Maps - Twilio
Register for SIGNAL by 8/31 for $250 off. Register now.

Sync Maps

A map stores unordered JSON objects accessible via a developer defined key.

Maps can be created, updated, subscribed to and removed via the client JavaScript SDK. Servers wishing to manage these objects can do so via the REST API.

Adding JSON to or Updating existing JSON in a map

syncClient.map('users').then(function(map) {
  map.set('david', {
    phone_number: 12345678,
    country: 'UK'
  }).then(function(item) {
    console.log('Added: ', item.key);
  }).catch(function(err) {
    console.error(err);
  });
});

Using set will overwrite any existing data in a map item.

Updating data in a map item

syncClient.map('users').then(function(map) {
  map.update('david',{country: "IRL"});
});

Use mutate for more control over updates.

syncClient.map('users').then(function (map) {
  map.mutate('david',function(remoteData) {
    remoteData.country = "USA";
    return remoteData;
  });
});

For more details on mutate and conflict resolution read up on Mutation and Conflict Resolution.

Subscribing to a map

syncClient.map('users').then(function (map) {
  map.on('itemAdded', function(item) {
    console.log('key', item.key);
    console.log('JSON data', item.value);
  });

//Note that there are two separate events for map item adds and map item updates:
  map.on('itemUpdated', function(item) {
    console.log('key', item.key);
    console.log('JSON data', item.value);
  });
});

Get items from a map

syncClient.map('users').then(function(map) {
  map.getItems().then(function(page) {
    console.log('show first item', page.items[0].key,
      page.items[0].value);
  });
});

Delete a map

syncClient.map('users').then(function (map) {
  map.removeMap().then(function () {
    console.log('map deleted');
  });
});

Get a particular item from a map

syncClient.map('users').then(function(map) {
  map.get('david').then(function(item) {
    console.log(item.value);
  });
});

Delete a particular item from a map

syncClient.map('users').then(function(map) {
  map.remove('david').then(function() {
    console.log('item deleted');
  });
});

See the JavaScript SDK documentation for a full reference.

Need some help?

We all do sometimes; code is hard. Get help now from our support team, or lean on the wisdom of the crowd browsing the Twilio tag on Stack Overflow.