Replies: 2 comments
-
|
The existing answer covers the basic case well. Here is a more complete, production-ready approach using a shared The Problem with Inline HeadersAdding headers directly in each // ❌ Repeated everywhere, hard to maintain
const response = await fetch(url, {
headers: { Authorization: `Bearer ${token}` }
});Recommended: Centralized Fetch FactoryCreate a typed fetch wrapper that handles auth headers, error handling, and response parsing in one place: // lib/api.ts
const API_KEY = import.meta.env.VITE_API_KEY; // or from your auth store
export async function apiFetch<T>(endpoint: string): Promise<T> {
const response = await fetch(`https://api.github.com${endpoint}`, {
method: "GET",
headers: {
Authorization: `Bearer ${API_KEY}`,
"Content-Type": "application/json",
Accept: "application/vnd.github+json",
},
});
// fetch does not throw on 4xx/5xx — this is critical for TanStack Query
if (!response.ok) {
throw new Error(`API error ${response.status}: ${response.statusText}`);
}
return response.json() as Promise<T>;
}Using the Factory with
|
Beta Was this translation helpful? Give feedback.
-
|
function Example() {
const { isPending, error, data } = useQuery({
queryKey: ['repoData'],
queryFn: async () => {
const res = await fetch('https://api.example.com/data', {
headers: {
Authorization: `Bearer ${API_KEY}`,
'Content-Type': 'application/json',
},
})
// fetch does NOT throw on 4xx/5xx, so check it yourself
if (!res.ok) throw new Error(`HTTP ${res.status}`)
return res.json()
},
})
if (isPending) return 'Loading...'
if (error) return 'An error occurred: ' + error.message
return <div>{/* ...data... */}</div>
}Two things people trip on:
With axios it's the same idea, put If that was what you needed, feel free to select it as the answer. |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
Goal:
Add header with bearer in realtion to api key
Problem:
How do you apply header with bearer api code below?
Code:
Other:
*The code should be react TS in relation to Tanstack query
*https://stackblitz.com/edit/tanstack-query-tzj47osm?file=src%2Findex.tsx&preset=node
Beta Was this translation helpful? Give feedback.
All reactions