Skip to content
Source
Sign inSign up
TanStack/db

Declaring custom rollback behavior #487

Send to my agent
Opencoryhouse(GitHub profile, opens in a new tab) opened this issue 4 comments

Tanstack DB rolls back the change by default if it fails. Two questions:

  1. Can I override the rollback and declare my own custom behavior?
  2. I'm redirecting to an index page after an optimistic edit. If the rollback occurs after the user has been redirected, how I can notify the user?
  1. Overide the rollback in what way? Like not immediately remove the optimistic state? The rollback happens when you throw from the mutationFn so that's the main mechanism for control.

    The transaction object (return from collection.insert, etc.) has the error you throw on it. https://tanstack.com/db/latest/docs/reference/classes/transaction#error

    So

    try {
      await transaction.isPersisted.promise
    } catch (error) {
      // do something with error
    }
  2. Scenario: When the user saves an edit, I redirect to a list page. If the optimistic save ultimately fails (which occurs after the redirect), the list page has no access to the transaction. So, there's no way for me to notify the user that the save ultimately failed.

    Only thing I can think of is storing the transaction in a global (like context) so I could access it on the list page. Is there a better way?

  3. Yeah older versions of this library had a global store of all transactions you could subscribe to — we removed that for the beta as the API was meh. We might revisit that idea as it'd let you have one error handler that shows e.g. a toas on errors. But in the meantime yeah, tossing the transaction onto some sort of global store so the list page can listen to it is the best pattern I know of.

  4. Ah, nice. Yeah, I was looking for something like the global store. In Tanstack Query, one can use the queryClient for global config. Feels like Tanstack DB needs something similar.

    Thanks for the quick reply @KyleAMathews!

Sign in to join this conversation.