⚡ Cap 05: Stack PERN: Express com TypeScript, PostgreSQL, Prisma ORM e React com TanStack Query - Exemplos Práticos
Código executável completo demonstrando a integração de sistemas Full Stack.
🗺️ Fluxo de Integração
flowchart TD
REACT["Frontend React + TanStack Query (useQuery / useMutation)"]
REACT -->|HTTP REST| EXPRESS["Backend Express + TypeScript + Zod Validation"]
EXPRESS --> PRISMA["Prisma ORM (Queries Type-Safe)"]
PRISMA --> PG["PostgreSQL 16"]
style REACT fill:#e1f5fe,stroke:#03a9f4,stroke-width:2px
style EXPRESS fill:#fff3e0,stroke:#ff9800,stroke-width:1px
style PRISMA fill:#e8f5e9,stroke:#4caf50,stroke-width:2px
📄 Código de Demonstração (useTarefasQuery.ts)
// useTarefasQuery.ts (Frontend React com TanStack Query)
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import axios from 'axios';
interface Tarefa {
id: number;
titulo: string;
concluida: boolean;
}
export function useTarefas() {
const queryClient = useQueryClient();
const tarefasQuery = useQuery({
queryKey: ['tarefas'],
queryFn: async () => {
const { data } = await axios.get<Tarefa[]>('/api/tarefas');
return data;
}
});
const criarTarefaMutation = useMutation({
mutationFn: async (novoTitulo: string) => {
const { data } = await axios.post<Tarefa>('/api/tarefas', { titulo: novoTitulo });
return data;
},
onSuccess: () => {
// Invalida cache para disparar refetch automático
queryClient.invalidateQueries({ queryKey: ['tarefas'] });
}
});
return { ...tarefasQuery, criarTarefa: criarTarefaMutation.mutate };
}
🚀 Saída Esperada de Execução
[TanStack Query Execution]
1. [Cache Miss] Fetching GET /api/tarefas... 200 OK (5 itens em cache)
2. [Mutation] POST /api/tarefas -> 201 Created
3. [Auto-Refetch] Invalidating 'tarefas' query -> UI atualizada instantaneamente!
🧭 Navegação Rápida
| 📖 Teoria | 📊 Slides | 🧠 Quiz | 💻 Exemplos | 🧩 Exercícios | | :— | :— | :— | :— | :— | | Ler Tópico | Ver Slides | Fazer Quiz | Ver Código | Praticar |