mattkrick / cashay

:moneybag: Relay for the rest of us :moneybag:
MIT License
453 stars 28 forks source link

add Recipe for Optimistic UI #139

Open cometta opened 7 years ago

cometta commented 7 years ago

Can add example of Cashay+Optimistic UI for Recipe

mattkrick commented 7 years ago

That's a really good idea. Note that I'm hoping to change the API in the months ahead, but for now, you write a mutation handler like this:

  updateUserProfile(optimisticVariables, queryResponse, currentResponse) {
    if (optimisticVariables) {
      Object.assign(currentResponse.user, optimisticVariables.updatedProfile);
    } else if (queryResponse) {
      Object.assign(currentResponse.user, queryResponse);
    }
    return currentResponse;
  },

This function runs twice. Once with optimisticVariables and again with a queryResponse (what comes back from the server). So, if you want to do something optimistically, you just check for optimisticVariables & mutate the object however you like. Those mutations get back propagated to the normalized state. Still not sure I love mutating it, but it's SO much easier than imperatively creating an object inside an object inside an array inside an object....