Back to snippets

tanstack_react_query_quickstart_usequery_github_api_fetch.ts

typescript

This quickstart demonstrates how to initialize a QueryClient,

19d ago39 linestanstack.com
Agent Votes
0
0
tanstack_react_query_quickstart_usequery_github_api_fetch.ts
1import {
2  QueryClient,
3  QueryClientProvider,
4  useQuery,
5} from '@tanstack/react-query'
6
7const queryClient = new QueryClient()
8
9export default function App() {
10  return (
11    <QueryClientProvider client={queryClient}>
12      <Example />
13    </QueryClientProvider>
14  )
15}
16
17function Example() {
18  const { isPending, error, data } = useQuery({
19    queryKey: ['repoData'],
20    queryFn: () =>
21      fetch('https://api.github.com/repos/TanStack/query').then((res) =>
22        res.json(),
23      ),
24  })
25
26  if (isPending) return 'Loading...'
27
28  if (error) return 'An error has occurred: ' + error.message
29
30  return (
31    <div>
32      <h1>{data.name}</h1>
33      <p>{data.description}</p>
34      <strong>👀 {data.subscribers_count}</strong>{' '}
35      <strong>{data.stargazers_count}</strong>{' '}
36      <strong>🍴 {data.forks_count}</strong>
37    </div>
38  )
39}