cugs
cugs
TtRPC
Created by cugs on 11/19/2023 in #❓-help
Multiple optimistic updates and old data from refetches
Hi all, I'm new to tRPC and React Query and I'm just trying to get my head around what exactly I'm doing wrong when trying to implement optimistic updates. To help illustrate the issue I'm having, I have a list of items that are deletable, and I want to be able to optimistically update the UI when they're deleted, which I have working, except for this one bug... When I delete one item, then delete a second item about 1-2 seconds later (i.e. before the first deletion has a chance to refetch the server data) I notice that the UI updates from the server with the state of only the first deletion, hence the UI optimistically deletes both items, then refetches, which shows one of the deleted items still there, then shortly after it correctly updates again to the correct state after the 2nd refetch. To solve this issue, I thought that I should be using .cancel() to prevent out-of-date data being returned by refetches that came before the latter mutation, but for whatever reason, that isn't working. (Likely cause I'm stoopid 🙃) To better illustrate, I've included a log of the order of execution: (You can see exactly where these console.logs are placed in my code which I'll also include below)
@acme/expo:dev: LOG onMutate <--- first deletion via UI
@acme/expo:dev: LOG onMutate <--- second deletion via UI
@acme/expo:dev: LOG onSettled <--- first deletion is settled
@acme/expo:dev: LOG refetch <--- this is the reason for the incorrect state being shown 😭
@acme/expo:dev: LOG onSettled <--- second deletion is settled
@acme/expo:dev: LOG refetch <--- this updates the UI to the correct state
@acme/expo:dev: LOG onMutate <--- first deletion via UI
@acme/expo:dev: LOG onMutate <--- second deletion via UI
@acme/expo:dev: LOG onSettled <--- first deletion is settled
@acme/expo:dev: LOG refetch <--- this is the reason for the incorrect state being shown 😭
@acme/expo:dev: LOG onSettled <--- second deletion is settled
@acme/expo:dev: LOG refetch <--- this updates the UI to the correct state
I've actually been stuck on this for an embarassingly long time, so any help would be GREATLY appreciated 🙏
8 replies