Skip to content

Instantly share code, notes, and snippets.

@dikaio
Last active August 15, 2023 23:54
Show Gist options
  • Save dikaio/6d2db2a2bd252d703a971c5745a3d5f6 to your computer and use it in GitHub Desktop.
Save dikaio/6d2db2a2bd252d703a971c5745a3d5f6 to your computer and use it in GitHub Desktop.
Fetch Random Data in Next.js (App Router)
// Thanks Alex
// https://twitter.com/asidorenko_/status/1691512559923322880?s=61&t=uyXggCFpWOJLCF9RVYpLTw
// `@/components/fetch-button.tsx`
// `next 13.4.16`
'use client'
import { useRouter } from 'next/navigation'
import { useTransition } from 'react'
export function FetchButton() {
const router = useRouter()
const [isPending, startTransition] = useTransition()
return (
<button disabled={isPending} onClick={() => startTransition(router.refresh)}>
{isPending && 'Loading...'}
{!isPending && 'Click to fetch a random dog'}
</button>
)
}
import Image from 'next/image'
import { FetchButton } from '@/components/fetch-button'
export default async function Dog() {
const res = await fetch(
'https://dog.ceo/api/breeds/image/random',
{ cache: 'no-store' } // this line removes next.js default cache value
)
const { message } = await res.json()
return (
<div className="mx-auto max-w-7xl">
<div className="relative h-96 w-96">
<Image
src={message}
alt="..."
quality={80}
fill={true}
sizes="(min-width: 66em) 33vw, (min-width: 44em) 50vw, 100vw"
/>
</div>
<FetchButton />
</div>
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment