function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Dominic Blythe .Dominic Blythe . 

Fetching records with merge, doesnt seem to merge Mobile SDK 2.1

I am building an app with MobileSDK 2.1, it's based on Account Editor sample app.

I can edit and save my record offline, but then if the app comes online and the collection it is part of is fetched from the server again, the server version overwrites the local changes.

I have been hoping that there's a way to get the Merge Mode taken into account so local changes are preserved but unchanged fields are updated from remote. The code that's processing the fetch in the smartsync library Force.StoreCache.saveAll has some code that looks like it's doing a merge with local records, at the record level, but the result is "all the remote fields".

I think it's pretty important that local edits aren't overwritten with older remote data. The example app seems to achieve this by not refreshing the main collection, but it's also important to keep that up to date, which is why I want the collision-detection to happen.
akhilesh_sfdcakhilesh_sfdc
--- EDITED ---

That's right Dominic. The default behavior of fetch is to overwrite all the records received from the server to local storage. Currently, there are couple ways to handle this scenario:
1) Perform save to server before running any fetch operations. This will make sure all the local changes are pushed to server and hence avoid any issues with overwrite during fetch.
2) Override the method "fetchRemoteObjectsFrom" on SObjectCollection to filter out the records from ajax response which are locally changed. Your code will look something like this:

var NewSObjectCollection = Force.SObjectCollection.extend({
            fetchRemoteObjectsFromServer: function(config) {
                 // Call the parent fetch method and filter the results
                 return Force.SObjectCollection.fetchRemoteObjectsFromServer(config).then(function(resp) {

                      var localCollection = // Fetch locally modified records using a following collection config: {type:"cache", cacheQuery: {queryType:"exact", indexPath:"__local__", matchKey:true, order:"ascending", pageSize:25}};

                      resp.records = resp.records.filter(function(rec) {
                           // return false if rec is in localCollection, else return true
                      });
                      // Reset the response size
                      resp.totalSize = resp.records.length;

                      // Similarly override the resp.getMore method to do the same filtering.
                      return resp;
                 });
            }
});