|
| 1 | +'use client' |
| 2 | +import { useQuery } from '@tanstack/react-query' |
| 3 | +import { Suspense } from 'react' |
| 4 | + |
| 5 | +// export const runtime = "edge"; // 'nodejs' (default) | 'edge' |
| 6 | + |
| 7 | +function getBaseURL() { |
| 8 | + if (typeof window !== 'undefined') { |
| 9 | + return '' |
| 10 | + } |
| 11 | + if (process.env.VERCEL_URL) { |
| 12 | + return `https://${process.env.VERCEL_URL}` |
| 13 | + } |
| 14 | + return 'http://localhost:3000' |
| 15 | +} |
| 16 | +const baseUrl = getBaseURL() |
| 17 | +function useWaitQuery(props: { wait: number }) { |
| 18 | + const query = useQuery({ |
| 19 | + queryKey: ['wait', props.wait], |
| 20 | + queryFn: async () => { |
| 21 | + const path = `/api/wait?wait=${props.wait}` |
| 22 | + const url = baseUrl + path |
| 23 | + |
| 24 | + console.log('fetching', url) |
| 25 | + const res: string = await ( |
| 26 | + await fetch(url, { |
| 27 | + cache: 'no-store', |
| 28 | + }) |
| 29 | + ).json() |
| 30 | + return res |
| 31 | + }, |
| 32 | + suspense: true, |
| 33 | + }) |
| 34 | + |
| 35 | + return [query.data as string, query] as const |
| 36 | +} |
| 37 | + |
| 38 | +function MyComponent(props: { wait: number }) { |
| 39 | + const [data] = useWaitQuery(props) |
| 40 | + |
| 41 | + return <div>result: {data}</div> |
| 42 | +} |
| 43 | + |
| 44 | +export default function MyPage() { |
| 45 | + return ( |
| 46 | + <> |
| 47 | + <Suspense fallback={<div>waiting 100....</div>}> |
| 48 | + <MyComponent wait={100} /> |
| 49 | + </Suspense> |
| 50 | + <Suspense fallback={<div>waiting 200....</div>}> |
| 51 | + <MyComponent wait={200} /> |
| 52 | + </Suspense> |
| 53 | + <Suspense fallback={<div>waiting 300....</div>}> |
| 54 | + <MyComponent wait={300} /> |
| 55 | + </Suspense> |
| 56 | + <Suspense fallback={<div>waiting 400....</div>}> |
| 57 | + <MyComponent wait={400} /> |
| 58 | + </Suspense> |
| 59 | + <Suspense fallback={<div>waiting 500....</div>}> |
| 60 | + <MyComponent wait={500} /> |
| 61 | + </Suspense> |
| 62 | + <Suspense fallback={<div>waiting 600....</div>}> |
| 63 | + <MyComponent wait={600} /> |
| 64 | + </Suspense> |
| 65 | + <Suspense fallback={<div>waiting 700....</div>}> |
| 66 | + <MyComponent wait={700} /> |
| 67 | + </Suspense> |
| 68 | + |
| 69 | + <fieldset> |
| 70 | + <legend> |
| 71 | + combined <code>Suspense</code>-container |
| 72 | + </legend> |
| 73 | + <Suspense |
| 74 | + fallback={ |
| 75 | + <> |
| 76 | + <div>waiting 800....</div> |
| 77 | + <div>waiting 900....</div> |
| 78 | + <div>waiting 1000....</div> |
| 79 | + </> |
| 80 | + } |
| 81 | + > |
| 82 | + <MyComponent wait={800} /> |
| 83 | + <MyComponent wait={900} /> |
| 84 | + <MyComponent wait={1000} /> |
| 85 | + </Suspense> |
| 86 | + </fieldset> |
| 87 | + </> |
| 88 | + ) |
| 89 | +} |
0 commit comments