Arpith Siromoney 💬

Speed Up Your App With Optimistic UI

My app’s flux store used to do this when deleting a post:

function deletePost(post) {
  // Create the API request
  var username = SettingStore.getUsername();
  var token = SettingStore.getToken();
  var body = JSON.stringify({token: token});
  var key = post.key;
  if (!key) key = post.created + post.id;
  var url = APIURL + ‘/’ + username + ‘/’ + key;
  var params = {method: ‘DELETE’, body: body, headers: HEADERS};
  
  // Make the API request
  fetch(url, params).then(() => {
    // Delete the post locally
    var i = _postURLs.indexOf(post.url);
    _postURLs.splice(i, 1);
    delete _posts[post.url];
    PostStore.emitChange();
    return updateAsyncStore();
  });
}

Basically, the app tells the API to delete the post, and when it gets the response, it removes the post from its list of posts. This is then reflected in the UI — which means the user has to wait for the API to respond to see the post removed from the list!

Let’s be optimistic instead, and remove the post from the local list first (before using the API to delete the online copy). This is what the code looks like now:

function deletePost(post) {
  // Delete the post locally
  var i = _postURLs.indexOf(post.url);
  _postURLs.splice(i, 1);
  delete _posts[post.url];
  PostStore.emitChange();
  
  // Create and make the API request
  var username = SettingStore.getUsername();
  var token = SettingStore.getToken();
  var body = JSON.stringify({token: token});
  var key = post.key;
  if (!key) key = post.created + post.id;
  var url = APIURL + ‘/’ + username + ‘/’ + key;
  var params = {method: ‘DELETE’, body: body, headers: HEADERS};
  fetch(url, params).then(updateAsyncStore);
}

Two things need to be worked out, (a) what happens when the API call fails and (b) how do you do this for creating or editing posts. Let me know if you have ideas!