swr
swr copied to clipboard
rollbackOnError as function
Discussed in https://github.com/vercel/swr/discussions/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,
});
}
}