Search code examples
javascriptrestextjsstore

ExtJS - How do I pass ID when syncing store?


On ExtJS 6.2, I'm getting data from database like this: myStore.load({id: myId);.

How do I pass the ID while syncing? This doesn't work: myStore.sync({id: myId);

I'm using a REST proxy and my URL is in this format: mydomain/users/1


Solution

  • I solved by extending Ext.data.proxy.Rest and overriding the buildUrl method to be able to extract the ID from the request parameters. Then I used this overridden proxy in my model:

    Ext.define('MYPROJ.proxy.Settings', {
       extend : 'Ext.data.proxy.Rest',
       alias  : 'proxy.settings',
       buildUrl(request) {
          const url = this.callParent([request]);
          const id  = request.getParams().id;
    
          if (id) {
             delete request.getParams().id;
    
             const proxyUrl = request.getProxy().getUrl();
    
             return url.replace(proxyUrl, `${proxyUrl}/${id}`);
          }
    
          return url;
       }
    });
    
    Ext.define('MYPROJ.model.Setting', {
       extend  : 'Ext.data.Model',
       alias   : 'model.setting',
    
       clientIdProperty: 'clientId',
    
       fields: [{
          name    : 'id',
          type    : 'int',
          persist : false
       }, {
          name   : 'name',
          type   : 'string',
          unique : true
       }],
    
       proxy: {
          type : 'settings', // <- Use overridden proxy here
          url  : `/something/settings`
       }
    });
    

    Then in my code I can use sync() like this:

    const myID = 10;
    
    this.settingsStore.load({id: myID});
    
    //...
    
    this.settingsStore.sync({params: {id: myID}});
    

    When sync() is called myID will be extracted from params on MYPROJ.proxy.Settings and added to the URL (/something/settings/10).