Created
January 29, 2024 04:07
-
-
Save corysimmons/ee6be735d06d21666ac91bc322d9b23b to your computer and use it in GitHub Desktop.
Just a hook to replace SWR and react-query in Next.js server components (Next.js' new `fetch` automatically handles caching and stuff).
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use server'; | |
import { useServerFetch } from '../hooks/useServerFetch'; | |
export default async function Page() { | |
const { loading, error, data } = useServerFetch<any>('/api/123'); | |
if (loading) return <h1>loading</h1>; | |
if (error) return <h1>{error.message}</h1>; | |
return <h1>{JSON.stringify(data)}</h1>; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// hooks/useServerFetch.ts | |
import { useEffect, useState } from 'react'; | |
export function useServerFetch<T>(url: string) { | |
const [data, setData] = useState<T | null>(null); | |
const [loading, setLoading] = useState(true); | |
const [error, setError] = useState<Error | null>(null); | |
useEffect(() => { | |
async function fetchData() { | |
try { | |
const response = await fetch(url); | |
if (!response.ok) { | |
throw new Error(`Error fetching data: ${response.statusText}`); | |
} | |
const json = await response.json(); | |
setData(json); | |
} catch (e) { | |
if (e instanceof Error) { | |
setError(e); | |
} | |
} finally { | |
setLoading(false); | |
} | |
} | |
fetchData(); | |
}, [url]); | |
return { data, loading, error }; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment