SWR
import DCat from '@/components/dcat'
<DCat />
Where the DCat component is:
/components/dcat.jsx
import useSWR from 'swr'
import Image from 'next/image'
const catURL= "https://api.thecatapi.com/v1/images/search?size=full"
const key = catURL; // The key param represents the URL, in the case of REST APIs, to which the request is to be made. The reason for the key name is because it actually is a key. It is a unique string that represents the data that is being fetched. If the key changes, the data will be refetched.
const fetcher = () => fetch(catURL).then((res) => res.json())
const options = { revalidateOnFocus: false }
export default function DCat() {
const { data, isLoading, error } = useSWR(key, fetcher, options);
if (isLoading) return <div>Loading...</div>
if (error) return <div>Error: {error}</div>
return <Image src={data[0].url} width={data[0].width} height={data[0].height}/>
}
Since the image is fetched from an external API, we have to allow
the image to be displayed by adding the following to the next.config.js
file:
next.config.js
import nextra from 'nextra'
export default nextra(
{ // Nextra configuration
theme: 'nextra-theme-docs',
themeConfig: './theme.config.jsx',
latex: true,
search: true
}
)(
{ // Next.js configuration
images: {
remotePatterns: [
{
protocol: 'https',
hostname: 'avatars.githubusercontent.com',
//port: '80',
pathname: '/u/**',
},
{
protocol: 'https',
hostname: 'cdn2.thecatapi.com',
//port: '80',
pathname: '/images/**',
},
]
}
}
)
See https://nextjs.org/docs/pages/api-reference/components/image#remotepatterns
Result
Loading...