Replies: 1 comment
-
|
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.
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