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

navigateTo in $fetch onResponseError is doesn't work #27991

Closed
nogolang opened this issue Jul 3, 2024 · 2 comments · Fixed by #28000
Closed

navigateTo in $fetch onResponseError is doesn't work #27991

nogolang opened this issue Jul 3, 2024 · 2 comments · Fixed by #28000

Comments

@nogolang
Copy link

nogolang commented Jul 3, 2024

Environment

Nuxt 3.12.3 with Nitro 2.9.7

Reproduction

see Describe

Describe the bug

this is offical example,But it didn't work
https://nuxt.com/docs/guide/recipes/custom-usefetch

this is plugins,to injecct nuxt

export default defineNuxtPlugin(() => {
    const router=useRouter()
    const api = $fetch.create({
        baseURL: 'http://127.0.0.1:4523/m1/4632367-4282747-default',
         async onResponseError({response}) {
            if (response.status === 401) {
                console.log("yes, is runing here,but navigateTo doesn't work")
                 await navigateTo('/login', {
                    redirectCode: 302,
                })
            }
        }
    })

    // Expose to useNuxtApp().$api
    return {
        provide: {
            api
        }
    }
})

The page does not change to login.vue when my http status is 401, navigateTo doesn't work
I'm pretty sure this is the official case

<script setup lang="ts">
let path="/user/1"
const { $api } = useNuxtApp()
const { data: modules } = await useAsyncData(path, () => $api(path))
</script>

Additional context

No response

Logs

No response

@Ayax0
Copy link

Ayax0 commented Jul 3, 2024

I once did something similar. as I understand it, the Nuxt plugins are not necessarily connected to the Nuxt instance. I solved the whole thing by calling the navigateTo function using callWithNuxt. That works for me.

export default defineNuxtPlugin(async (nuxtApp) => {
    await callWithNuxt(nuxtApp, () => navigateTo("/login"));
});

@danielroe
Copy link
Member

We should update the example.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging a pull request may close this issue.

3 participants