Menu

Rate this page:

Thanks for rating this page!

We are always striving to improve our documentation quality, and your feedback is valuable to us. How could this documentation serve you better?

Sync Lists

A list allows users to push JSON into an ordered list and update existing items within the list.

Lists 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.

Pushing JSON into a list

syncClient.list('example_list').then(function(list) {
  list.push({
    text: 'hello world',
    user: 'Charles Xavier'
  }).then(function(item) {
    console.log('Added: ', item.index);
  }).catch(function(err) {
    console.error(err);
  });
});

Subscribing to a list

syncClient.list('example_list').then(function(list) {
  list.on('itemAdded', function(item) {
    console.log('index', item.index);
    console.log('JSON data', item.value);
  });

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

Get items from a list

syncClient.list('example_list').then(function(list) {
  list.getItems().then(function(page) {
    console.log('show first item', page.items[0]);
  });
});

Delete a list

syncClient.list('example_list').then(function(list) {
  list.removeList().then(function() {
    console.log('deleted list');
  });
});

Get a single item

syncClient.list('example_list').then(function(list) {
  list.get(0).then(function(item) {
    console.log('show first item', item);
  });
});

Change data in a single item

syncClient.list('example_list').then(function (list) {
  var newValue = {
    text: 'hello world',
    user: 'Wolverine'
  };
  list.set(0, newValue).then(function(item) {
    console.log('updated first item', item);
  });
});

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

Updating data in a list item

syncClient.list('example-list').then(function(list) {
  list.update(0,{user: "Magneto"});
});

Use mutate for more control over updates.

syncClient.list('example-list').then(function (list) {
  list.mutate(0,function(remoteData) {
    remoteData.user = "Cyclops";
    return remoteData;
  });
});

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

Delete a single item

syncClient.list('example_list').then(function(list) {
  list.remove(0).then(function() {
    console.log('deleted first item');
  });
});

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.

Loading Code Sample...