question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Extending useFetch

See original GitHub issue

Environment

Nuxt CLI v3.0.0-27338323.1e98259

Reproduction

I’m trying to extend useFetch

const useApiFetch = async (url: string, options) => {
    const config = useRuntimeConfig()

    return useFetch(url, {
        baseURL: config.API_URL,
        async onRequest(ctx) {
            const accessToken = await useCookie('access_token' ,{ default: undefined })

            if (undefined !== accessToken) {
                ctx.options.headers.append('Authorization', accessToken.value)
                // ctx.options.headers.set('Authorization', accessToken.value)
                // ctx.options.headers['Authorization'] = `Bearer ${accessToken.value}`
            }
        },
        ...options
    });
}

export default useApiFetch

And use it to retrieve data.

const { data } = await useApiFetch("item/item-categories/search", {
        params: {
          query:'Hello world',
          limit: 5
        }
      });

I can set params in interceptors, but I can’t set headers. If I set headers, fetch doesn’t work, it even doesn’t fires request.

Describe the bug

Impossible to extend useFetch with interceptors

Additional context

No response

Logs

No response

Issue Analytics

  • State:closed
  • Created 2 years ago
  • Comments:5 (1 by maintainers)

github_iconTop GitHub Comments

2reactions
danielroecommented, Jan 4, 2022

You also shouldn’t be calling useCookie within the request, but rather within the setup portion of your composable, and note that it returns a Ref - e.g.:

const useApiFetch = async (url: string, options) => {
    const config = useRuntimeConfig()
+   const accessToken = useCookie('access_token')

    return useFetch(url, {
        baseURL: config.API_URL,
        async onRequest(ctx) {
-            const accessToken = await useCookie('access_token' ,{ default: undefined })
+            if (!accessToken.value) {
-            if (undefined !== accessToken) {
                ctx.options.headers.append('Authorization', accessToken.value)
                // ctx.options.headers.set('Authorization', accessToken.value)
                // ctx.options.headers['Authorization'] = `Bearer ${accessToken.value}`
            }
        },
        ...options
    });
}

export default useApiFetch

If you need a hand, do feel free to create a GitHub Discussion, or post a reproduction if you think there’s a bug.s

1reaction
rnotornicommented, Jan 3, 2022

Probably due to undefined in ctx.options.headers.

Since the version up of ohmyfetch has been done, it seems that the current situation is working.

I think that it will work if you do the following.

const useApiFetch = async (url: string, options) => {
    const config = useRuntimeConfig()

    return useFetch(url, {
        baseURL: config.API_URL,
        async onRequest(ctx) {
            const accessToken = await useCookie('access_token' ,{ default: undefined })

            if (undefined !== accessToken) {
+               ctx.options.headers = new Headers(ctx.options.headers)
                ctx.options.headers.append('Authorization', accessToken.value)
                // ctx.options.headers.set('Authorization', accessToken.value)
                // ctx.options.headers['Authorization'] = `Bearer ${accessToken.value}`
            }
        },
        ...options
    });
}

export default useApiFetch
Read more comments on GitHub >

github_iconTop Results From Across the Web

extending useFetch and using $fetch #2121 - GitHub
As I work on a plugin for my API - I was hoping to integrate and pass through fetch so I can easily...
Read more >
useFetch - Raycast API
useFetch. Hook which fetches the URL and returns the AsyncState corresponding to the execution of the fetch. The last value will be kept...
Read more >
useFetch() - Declarative fetch triggers - Rest Hooks
When using React Navigation, useFetch() will trigger fetches on focus if the data is considered stale. tip. Use in combination with a data-binding...
Read more >
React Custom Hook - useFetch - DEV Community ‍ ‍
We'll create another file called useFetch.js . You want to start the name of a custom hook with "use" so that React knows...
Read more >
useFetch
React hook for making isomorphic http requests.
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found