Skip to content
Source
Sign inSign up
TanStack/query
Open History to see the last commit

quick-start.md

76 lines1.5 KB

1---
2id: quick-start
3title: Quick Start
4ref: docs/framework/react/quick-start.md
5replace: { 'react-query': 'preact-query', 'React': 'Preact' }
6---
7​
8[//]: # 'Example'
9​
10If you're looking for a fully functioning example, please have a look at our [simple StackBlitz example](./examples/simple)
11​
12```tsx
13import {
14 useQuery,
15 useMutation,
16 useQueryClient,
17 QueryClient,
18 QueryClientProvider,
19} from '@tanstack/preact-query'
20import { render } from 'preact'
21import { getTodos, postTodo } from '../my-api'
22​
23// Create a client
24const queryClient = new QueryClient()
25​
26function App() {
27 return (
28 // Provide the client to your App
29 <QueryClientProvider client={queryClient}>
30 <Todos />
31 </QueryClientProvider>
32 )
34​
35function Todos() {
36 // Access the client
37 const queryClient = useQueryClient()
38​
39 // Queries
40 const query = useQuery({ queryKey: ['todos'], queryFn: getTodos })
41​
42 // Mutations
43 const mutation = useMutation({
44 mutationFn: postTodo,
45 onSuccess: () => {
46 // Invalidate and refetch
47 queryClient.invalidateQueries({ queryKey: ['todos'] })
48 },
49 })
50​
51 return (
52 <div>
53 <ul>
54 {query.data?.map((todo) => (
55 <li key={todo.id}>{todo.title}</li>
56 ))}
57 </ul>
58​
59 <button
60 onClick={() => {
61 mutation.mutate({
62 id: Date.now(),
63 title: 'Do Laundry',
64 })
65 }}
66 >
67 Add Todo
68 </button>
69 </div>
70 )
72​
73render(<App />, document.getElementById('root'))
74```
75​
76[//]: # 'Example'