Visualizzare dati da API in Next.js con useSWR
In questo articolo vediamo come visualizzare dati da API in Next.js usando SWR!
Come vedete viene descritto come un "React Hooks for Data Fetching"!
Per installare la llibreria possiamo usare npm:
npm i swr
Qui sotto un esempio:
"use client";
import useSWR from "swr";
type Canzone = {
canzone_titolo: string,
canzone_autore: string
}
const fetcher = (key: string) => fetch(key).then((res) => res.json());
export default function Home() {
const url = "https://www.matteoferrone.it/api/canzoni/get.php";
const {data, error, isLoading} = useSWR<Canzone>(url, fetcher);
const loadingComponent = <div>Loading...</div>;
const errorComponent = <div>Errore: {error?.name}</div>;
return (
<>
{isLoading ? (
loadingComponent
) : error ? (
errorComponent
) : (
<div>
<ul>
{data?.data.map(d => (<li key={d?.canzone_titolo}>{d?.canzone_titolo}</li>))}
</ul>
</div>
)}
</>
)
}
Enjoy!
javascript typescript npm react nextjs swr
Commentami!