Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

rollbackOnError as function #2093

Closed
huozhi opened this issue Jul 29, 2022 Discussed in #2092 · 0 comments · Fixed by #2242
Closed

rollbackOnError as function #2093

huozhi opened this issue Jul 29, 2022 Discussed in #2092 · 0 comments · Fixed by #2242
Labels
feature request New feature or request

Comments

@huozhi
Copy link
Member

huozhi commented Jul 29, 2022

Discussed in #2092

Originally posted by RenaudAubert July 29, 2022
Hi 👋
First of all a big thanks for this amazing library.

I've noticed that 2 of the mutate options (populateCache, optimisticData) can accept functions and I was wondering if it'd make sense to also have this possibility for rollbackOnError?

Use Case
Let's say I have a mobile app that can be used in areas with a bad network coverage. When user performs an action thanks to optimisticData the cache and view are updated directly and if an error occurs with rollbackOnError data is rolled-back. But errors can occur for many reasons, sometimes the API returns a valid error sometimes the error come from the network for instance TimeoutError.

I thought maybe something like this

const newData = createNewData(...);
mutate(key, updateFn(newData), {
    revalidate: true,
    populateCache: true,
    optimisticData: newData,
    rollbackOnError(error, currentData) {
        if (error.name === "TimeOutError") {
            return true;
        }

        return false;
    },
});

I'm not sure such an implementation could work, please feel free to let me know or suggest alternatives. Maybe I'm going at it completely wrong.
What I'm currently implementing is something like the following

const newData = createNewData(...);
try {
    const mutatedData = await mutate(key, data, {
        populateCache: true,
        optimisticData: newData,
        rollbackOnError: false,
    });
} catch (error) {
    // Error might comme from unique constraint in database, unsufficient permissions, etc...
    if (error.name !== "TimeoutError") {
        mutate(key, newData, {
            revalidate: false,
            populateCache: true,
            rollbackOnError: false,
        });
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
feature request New feature or request
Projects
None yet
Development

Successfully merging a pull request may close this issue.

1 participant