Instructor: So far, we've hooked our UI up to support deleting items from this list, and we're optimistically removing them from state. In the event of a failure, we display an error, and restore the item to state. Our original approach to this optimistic update is working fine for us, and can work fine for a number of scenarios.
If we dig into this, we'll see that we have left a hole. If I click item three and four real quick, item three is restored, but even though item four request has succeeded, we visually restored that to state, which would be incorrect at this point. That could have been deleted from the database.
We want to make sure that when we click, and in rapid succession, click more, that only the failed item is restored to state. If we follow this, if I click item three, and four and five in rapid succession, what's happening is, we take a snapshot when we clicked item three.
While that request was pending, the user took additional actions, and clicked item four and five, but this request failed. Those original items that we have in scope here from clicking item three included the items that have since been deleted. We need to look at taking a more granular approach.
Rather than snapshotting the entire array of items, what we want to do is, let's go ahead and grab the deleting item. This'll be the individual item that we're deleting from the list. We can grab that using items.find.
In using that, what we can do is, instead of just replacing this outright, let's go ahead and take state.items. We'll just spread that out here for now. We will append this to the list for now, just to make sure we're on the right track.
Now, if I click this, we'll see that only item three was restored to the list, but it was appended to the end. If we take another look at this, we can see that item one and two were successfully deleted, but item three is currently being appended to the list.
What we can do for that is -- and this is just a case-by-case basis -- in our case, we know that these are coming down just in the order of their IDs. Since we've just created this new array by spreading out state.items, and appending this onto it, we can go ahead and use the array sort method, which is going to take A and B.
We can sort them. We can just say A ID minus B ID. That's going to give us our ascending sorting that we're looking for here. Try that out. Now, one, two, three. Three gets inserted right as we expect it. If we may two, three, four, it gets inserted right in the middle, just as we'd expect it to.