Practical ReactJS and Redux (Optimistic Updates), Part 3

Tips for Optimistic Updates

This is the third in a series of blog posts about real-world ReactJS usage and what we’ve learned scaling our app at Threat Stack. Specifically, this is a quick followup that provides tips on how to achieve optimistic updates and rollbacks with what we’ve worked on in Parts 1and 2 of this series.

exportdefaultfunction(state = initialState, action){const{ payload }= action;switch(action.type){// NOTE: `UPDATE_ITEM_SUCCESS` is not used// We'll update the state tree using// what was sent to the server by pulling it from `payload`case UPDATE_ITEM:return{
item : payload.item,
err :null}// If there was an error, we can revert the state to the previous itemcase UPDATE_ERROR
return{
item : payload.prevItem,
err : action.err
}default:return state;}}

Where We Ended Up . . .

There are libraries and middleware to account for this type of thing.

But I think the real win here comes from using the same building blocks, in this case, payload, to accomplish different things.

It becomes clear to a dev reading the code what’s going on when you’re passing a prop called prevItem along.

Cris is a software engineer who currently codes in JavaScript, thinks ZeroCool could beat Elliot, and that clean code is always possible.
He’s either hanging out with his family, chasing wind, or writing code, preferably in that order.
Sometimes he posts James Franco gifs or code-related things @cris_o