Repository navigation
How to properly handle 404 routes with reroute() ? #2720
What we're trying to doWhen a Post API returns 404, we want to redirect to our catch-all not-found page instead of rendering the Post route. // loaders/post-loader.ts
import { reroute } from 'vue-router/experimental'
import { defineColadaLoader } from 'vue-router/experimental/pinia-colada'
export const usePostData = defineColadaLoader('posts.show', {
key: (to) => ['posts', to.params.id],
async query(to) {
const response = await api.getPost({ id: to.params.id as string })
if (response.status === 404) {
// navigate to not found page with the same URL
reroute({ name: 'not-found', params: { path: to.fullpath.split('/').filter(Boolean) } })
}
if (response.status !== 200) {
throw new Error('Failed to fetch post')
}
return response.body.data
},
staleTime: 60_000,
})<!-- pages/posts/[id].vue -->
<script lang="ts">
import { usePostData } from '@/loaders/post-loader'
export { usePostData }
</script><!-- pages/[[...path]]+.vue -->
<script setup>
definePage({ name: 'not-found' })
</script>ProblemNavigating to /posts/:id with a missing Post (HTTP 404) does not show the not-found page. The Post route still renders or shows a query error. We tried reroute({ name: 'not-found', params: { path: ... } }), same result. Using only reroute({ name: 'not-found' }) did not fix it either. QuestionsWhat's the recommended way to handle API 404s with defineColadaLoader and reroute(), or return new NavigationResult(...)? Is there a known gotcha when the same loader is also used from child components (not only exported from the page)? Any recommended pattern for passing the attempted URL into a catch-all not-found route? Environment
|
Replies: 1 comment 3 replies
|
|
Oh yes my bad 😅
I fix my initial issue, @pinia/colada version was 1.0.0 → upgraded to latest version now works well
Thanks for your help!