Shaddix / react-query-swagger

Generates react-query hooks based on Swagger API definitions
MIT License
131 stars 6 forks source link

How to pass authorization header to every single API calls? #51

Open gablabelle opened 2 months ago

gablabelle commented 2 months ago

Hello,

Could you share an example of how you actually pass headers to requests? For example, I need to pass an authorization header to all my API calls which is a pretty common pattern.

For now we do the following:

import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import * as Client from '@my/client'
import { useToken } from './token'

const queryClient = new QueryClient()

Client.setBaseUrl('https://example.com')

export function ClientProvider({ children }: { children: React.ReactNode }) {
  const { token } = useToken()

  if (token) {
    Client.setFetchFactory(() => ({
      fetch: (input: RequestInfo | URL, init?: RequestInit) => {
        const headers = new Headers(init?.headers)
        headers.set('Authorization', `Bearer ${token}`)
        return window.fetch(input, { ...init, headers })
      },
    }))
  }

  return <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
}

Many thanks for your time and help.

andreas-bergstrom commented 1 week ago

If you use Axios you can set it on the Axios client as in any general example for it