Lo que aprenderas en este tutorial
✓ Fundamentos de SWR
✓ Data fetching
✓ Mutaciones
✓ Control de cache
✓ Revalidacion
Step 1: Configuracion
npm install swr
Step 2: Uso basico
import useSWR from 'swr';
const fetcher = (url: string) => fetch(url).then(res => res.json());
function Profile() {
const { data, error, isLoading } = useSWR('/api/user', fetcher);
if (isLoading) return <div>Loading...</div>;
if (error) return <div>Error: {error.message}</div>;
return <div>Hello, {data.name}</div>;
}
Step 3: Configuracion global
// app/providers.tsx
import { SWRConfig } from 'swr';
const fetcher = async (url: string) => {
const res = await fetch(url);
if (!res.ok) throw new Error('Failed to fetch');
return res.json();
};
export function Providers({ children }: { children: React.ReactNode }) {
return (
<SWRConfig
value={{
fetcher,
revalidateOnFocus: true,
revalidateOnReconnect: true,
dedupingInterval: 2000,
}}
>
{children}
</SWRConfig>
);
}
Step 4: Fetch condicional
function UserPosts({ userId }: { userId: string | null }) {
// Si userId es null, no hacer fetch
const { data } = useSWR(
userId ? `/api/users/${userId}/posts` : null
);
return <div>{/* ... */}</div>;
}
Step 5: Mutaciones
import useSWR, { useSWRConfig } from 'swr';
function UpdateProfile() {
const { mutate } = useSWRConfig();
const updateUser = async (newData: any) => {
await fetch('/api/user', {
method: 'PUT',
body: JSON.stringify(newData),
});
// Revalidar cache
mutate('/api/user');
};
return <button onClick={() => updateUser({ name: 'New Name' })}>Update</button>;
}
Step 6: Actualizacion optimista
function TodoList() {
const { data, mutate } = useSWR('/api/todos');
const addTodo = async (text: string) => {
const newTodo = { id: Date.now(), text, completed: false };
// Actualizar optimistamente
mutate([...data, newTodo], false);
// Llamada a la API
await fetch('/api/todos', {
method: 'POST',
body: JSON.stringify({ text }),
});
// Revalidar
mutate();
};
return (/* ... */);
}
Step 7: Paginacion
import useSWRInfinite from 'swr/infinite';
function InfiniteList() {
const getKey = (pageIndex: number, previousPageData: any) => {
if (previousPageData && !previousPageData.length) return null;
return `/api/posts?page=${pageIndex}`;
};
const { data, size, setSize, isLoading } = useSWRInfinite(getKey);
const posts = data ? data.flat() : [];
const isLoadingMore = isLoading || (size > 0 && data && typeof data[size - 1] === 'undefined');
return (
<div>
{posts.map((post) => (
<div key={post.id}>{post.title}</div>
))}
<button
onClick={() => setSize(size + 1)}
disabled={isLoadingMore}
>
{isLoadingMore ? 'Loading...' : 'Load More'}
</button>
</div>
);
}
Step 8: Prefetch
import { preload } from 'swr';
// Prefetch al hacer hover con el mouse
function UserCard({ userId }: { userId: string }) {
const handleMouseEnter = () => {
preload(`/api/users/${userId}`, fetcher);
};
return (
<a href={`/users/${userId}`} onMouseEnter={handleMouseEnter}>
View Profile
</a>
);
}
Resumen
SWR es una biblioteca ligera de data fetching creada por Vercel. Automatiza el cache y la revalidacion mediante la estrategia stale-while-revalidate.
← Volver a la lista