Best way to handle error responses in Pinia Colada? #218
-
Hey all! 👋 I have a question around best practices or approaches to error handling in Pinia Colada. Let's say you have a page that fetches a list of something - and if there's an error, you want to redirect them to an error page. Curious if there's a better pattern or "Pinia Colada way" to do this? 🙏 export function useQueryWithErrorHandling<T>({
key,
queryFn,
staleTime = 5000,
onError,
}: QueryOptions<T>) {
const query = useQuery({
key,
query: queryFn,
staleTime,
})
watch(query.error, (error) => {
if (error && onError) {
onError(error)
} else {
console.error('Error fetching data:', error)
}
})
return query
}`` |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
There is intentionally no Here is an example using the plugin mentioned above: import { PiniaColada, PiniaColadaQueryHooksPlugin } from '@pinia/colada'
const app = createApp(App)
// app setup with other plugins
app.use(PiniaColada, {
plugins: [
PiniaColadaQueryHooksPlugin({
onError(error, entry) {
// ...
},
}),
],
}) So yes, using a |
Beta Was this translation helpful? Give feedback.
There is intentionally no
onError()
hook in queries because you don't need them. Not only Vue already haswatch
for side effects likeonError()
,onSuccess
, etc. But also, in practice, we don't want to have side effects in queries either, we want to keep our code declarative. We might want to have global query hooks, and that's a different story with the query hooks plugin. In mutations, side effects (like changing the cache) are much more common and they also allow us to delay the mutation (returning a promise in any of the hooks will makemutateAsync
a resolve or reject after it).Here is an example using the plugin mentioned above: