Skip to content

Declaring custom rollback behavior #487

Description

@coryhouse

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?

Activity

  1. KyleAMathews commented on Sep 3, 2025

    @KyleAMathews
    Collaborator

    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. coryhouse commented on Sep 3, 2025

    @coryhouse
    ContributorAuthor

    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. KyleAMathews commented on Sep 3, 2025

    @KyleAMathews
    Collaborator

    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. coryhouse commented on Sep 3, 2025

    @coryhouse
    ContributorAuthor

    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 up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions