N
Nuxt2y ago
Vonox

Redirect user when useFetch fails

I'm trying to figure out how to redirect the user when useFetch fails. For example I have:
<script setup>
const route = useRoute()
const { data } = useFetch('/api/products', {
query: {
id: route.params.id
}
})
</script>
<script setup>
const route = useRoute()
const { data } = useFetch('/api/products', {
query: {
id: route.params.id
}
})
</script>
Here I'm using the route param id the fetch a certain product. However, if I change the route param to an invalid id, the useFetch will fail and I want to redirect the user away from the page. How can I achieve this? I have tried the following without result:
<script setup>
const route = useRoute()
const { data } = useFetch('/api/products', {
query: {
id: route.params.id
},
onResponseError() {
const router = useRouter()
router.push('/')
}
})

// More code here
</script>
<script setup>
const route = useRoute()
const { data } = useFetch('/api/products', {
query: {
id: route.params.id
},
onResponseError() {
const router = useRouter()
router.push('/')
}
})

// More code here
</script>
This doesn't seem to stop the rest of my script inside of <script setup> from executing.
5 Replies
Unknown User
Unknown User2y ago
Message Not Public
Sign In & Join Server To View
Vonox
VonoxOP2y ago
Great example! However error seems to be null in my template. I'm not exactly sure how to throw an error from my API endpoint, any idea? Right now it looks something like this: server/api/products.js
import { firestore } from '../utils/firebase'

export default defineEventHandler(async event => {
const query = getQuery(event)

const snapshot = await firestore.collection('products').doc(query.id).get()

if (snapshot.exists) {
// code
} else {
throw new Error(`Product with id ${query.id} does not exist`)
}
})
import { firestore } from '../utils/firebase'

export default defineEventHandler(async event => {
const query = getQuery(event)

const snapshot = await firestore.collection('products').doc(query.id).get()

if (snapshot.exists) {
// code
} else {
throw new Error(`Product with id ${query.id} does not exist`)
}
})
I can see my error message in the console, but other than that nothing happens
Unknown User
Unknown User2y ago
Message Not Public
Sign In & Join Server To View
Vonox
VonoxOP2y ago
Works like a charm! Thank you very much 😁
Unknown User
Unknown User2y ago
Message Not Public
Sign In & Join Server To View
Want results from more Discord servers?
Add your server