快速入门
此代码片段简要说明了 Preact Query 的三个核心概念:
如果你需要一个完整可运行的示例,请查看我们的 简单 StackBlitz 示例。
TypeScript
1import {2 useQuery,3 useMutation,4 useQueryClient,5 QueryClient,6 QueryClientProvider,7} from '@tanstack/ppreact-query'8import { render } from 'preact'9import { getTodos, postTodo } from '../my-api'10 11// Create a client12const queryClient = new QueryClient()13 14function App() {15 return (16 // Provide the client to your App17 <QueryClientProvider client={queryClient}>18 <Todos />19 </QueryClientProvider>20 )21}22 23function Todos() {24 // Access the client25 const queryClient = useQueryClient()26 27 // Queries28 const query = useQuery({ queryKey: ['todos'], queryFn: getTodos })29 30 // Mutations31 const mutation = useMutation({32 mutationFn: postTodo,33 onSuccess: () => {34 // Invalidate and refetch35 queryClient.invalidateQueries({ queryKey: ['todos'] })36 },37 })38 39 return (40 <div>41 <ul>42 {query.data?.map((todo) => (43 <li key={todo.id}>{todo.title}</li>44 ))}45 </ul>4647 <button48 onClick={() => {49 mutation.mutate({50 id: Date.now(),51 title: 'Do Laundry',52 })53 }}54 >55 Add Todo56 </button>57 </div>58 )59}60 61render(<App />, document.getElementById('root'))这三个概念构成了 Preact Query 大部分核心功能。文档后续章节将对每个核心概念进行详细讲解。