Replies: 2 comments
-
|
Hey @jt4000! Adding a Bearer token is quite straightforward. You just need to pass an options object as the second argument to your fetch call inside the queryFn. Also, since you are using fetch, it's a good practice to manually check if the response is "ok". Unlike axios, fetch doesn't throw an error on 4xx or 5xx status codes, and TanStack Query needs a rejected promise to trigger the error state. Here is the updated code for your Example function: function Example() {
const { isPending, error, data, isFetching } = useQuery({
queryKey: ['repoData'],
queryFn: async () => {
const response = await fetch(
'https://api.github.com/repos/TanStack/query',
{
method: 'GET',
headers: {
'Authorization': `Bearer YOUR_API_KEY_HERE`,
'Content-Type': 'application/json',
},
}
);
if (!response.ok) {
throw new Error('Network response was not ok');
}
return await response.json();
},
});
if (isPending) return 'Loading...';
if (error) return 'An error has occurred: ' + error.message;
return (
<div>
<h1>{data.full_name}</h1>
<p>{data.description}</p>
<strong> {data.subscribers_count}</strong>{' '}
<strong> {data.stargazers_count}</strong>{' '}
<strong> {data.forks_count}</strong>
<div>{isFetching ? 'Updating...' : ''}</div>
</div>
);
} |
Beta Was this translation helpful? Give feedback.
-
|
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.
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