Showing posts with label sync. Show all posts
Showing posts with label sync. Show all posts

Friday, April 1, 2016

EXTJS: Get response from store sync operation

EXTJS sync operation is usually used to synchronize the Store with its Proxy. This asks the Proxy to batch together any new, updated and deleted records in the store, updating the Store's internal representation of the records as each operation completes. [ref. EXTJS store sync() API]

The sync operations can happen over REST calls. In case of a REST call, if the sync operations fails, how to achieve the response? Here is the way:
 store.sync({  
   success: function(batch, operations){  
      Ext.msg.Alert("store sync successful");  
   },  
   failure: function(batch, operations){  
      var response = rec.operations[0].error.response;  
      var responseText = JSON.parse(response.responseText);  
      var errorMessage = responseText.message;  
   }  
 });  


Happy coding :)

Thursday, March 31, 2016

EXTJS: sync operation multiple requests fired

Let me start with an example. Here is my sample model.

Ext.define('ExampleApp.model.Property', {
    extend: 'Ext.data.Model',
    idProperty: 'name',
    fields: [
        {name: 'name', type: 'string'},
        {name: 'value', type: 'string'}
    ],
    autoLoad: false,
    proxy: {
        type: 'rest',
        url: {sampleURL},
        batchActions: true, //batch all requests into one request
        reader: {
            type: 'json',
            rootProperty: ''
        },
        writer: {
            type: 'json',
            encode: false,
            writeAllFields: true,
            allowSingle: false //even if single object send it as an array
        }
    }
});

Here is my sync operation:

 var store = this.getExampleStore();  
 var newRecord = Ext.create('ExampleApp.model.Property');  
 var propertyName = rec.name;  
 var propertyValue = rec.value;  
 newRecord.set("name", propertyName);  
 newRecord.set("value", propertyValue);  
 store.add(newRecord);  
 store.sync({  
   success: function(batch, operations){  
      Ext.msg.Alert("store sync successful");  
   },  
   failure: function(batch, operations){  
      store.rejectChanges();  
   }  
 });  

To avoid the multiple requests for sync to be fired, here is the fix:
 batchActions: true 

This one config will not allow multiple requests to be fired. But all the new records added would be sent as a single request. But, what if you want only the last added record to be sent to the server. Consider this scenario: The record first added may have failed. You change the record data and add it to the store again. batchActions: true will send all the records as a batch. So all the previous records will also be sent.
 store.rejectChanges(); 


In the failure callback method of the sync operation, I called the above method, that removes all the records added till now. Hence only 1 record in the store remains to be sent to the server.

Happy coding :)