Created
February 2, 2026 13:15
-
-
Save DarkAng3L/4479c8ad39fa31035e40e5ba1464dda4 to your computer and use it in GitHub Desktop.
react-query factory example with queryOptions()
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import { useQuery, queryOptions, QueryClient } from '@tanstack/react-query' | |
| type Todo = { | |
| id: number | |
| } | |
| declare function fetchTodos(filters?: string): Promise<Array<Todo>> | |
| declare function fetchTodo(id: number): Promise<Array<Todo>> | |
| const queryClient = new QueryClient() | |
| const todoKeys = { | |
| all: ['todos'], | |
| filter: (filters: string) => [...todoKeys.all, 'filter', filters], | |
| detail: (id: number) => [...todoKeys.all, 'detail', id], | |
| } as const | |
| export const todoQueries = { | |
| all: () => | |
| queryOptions({ | |
| queryKey: todoKeys.all, | |
| queryFn: () => fetchTodos(), | |
| }), | |
| filter: (filters: string) => | |
| queryOptions({ | |
| queryKey: todoKeys.filter(filters), | |
| queryFn: () => fetchTodos(filters), | |
| }), | |
| detail: (id: number) => | |
| queryOptions({ | |
| queryKey: todoKeys.detail(id), | |
| queryFn: () => fetchTodo(id), | |
| staleTime: 5000, | |
| }), | |
| } | |
| const { data: todos } = useQuery(todoQueries.all()) | |
| const { data: firstTodo } = useQuery(todoQueries.detail(1)) | |
| const allTodoKeys = queryClient.getQueryData(todoQueries.all().queryKey) // allTodoKeys is same as todoKeys.all | |
| // ^? |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment