00
:
00
:
00
:
00
Corso SEO AI - Usa SEOEMAIL al checkout per il 30% di sconto

Queries e DevTools

useQuery

La hook fondamentale è useQuery. Richiede due cose:

  1. queryKey: Un array univoco che identifica i dati (es. ['todos'] o ['todo', 1]).
  2. queryFn: Una funzione che ritorna una Promise con i dati.

```tsx import { useQuery } from ‘@tanstack/react-query’

function Todos() { const { isPending, error, data } = useQuery({ queryKey: [‘todos’], queryFn: () => fetch(‘https://api.example.com/todos’).then((res) => res.json(), ), })

if (isPending) return ‘Caricamento…’

if (error) return 'Errore: ’ + error.message

return (

    {data.map((todo) => (
  • {todo.title}
  • ))}
) } ```

DevTools

TanStack Query ha dei DevTools fantastici che ti mostrano lo stato della cache in tempo reale.

```bash npm install @tanstack/react-query-devtools ```

Aggiungili al provider (non verranno inclusi nel bundle di produzione automaticamente):

```tsx import { ReactQueryDevtools } from ‘@tanstack/react-query-devtools’

\`\`\`