How do i do a simple and effective REST get in Next.js 14?
- User
How do i do a simple and effective REST get in Next.js 14?
Assistant
Here is a simple way to make a REST GET request in Next.js 14:
import useSWR from 'swr'; function MyComponent() { const { data, error } = useSWR('/api/users', fetch); if (error) return <div>Failed to load</div> if (!data) return <div>Loading...</div> return <div>{data.map(user => user.name)}</div> }The key things to note:
- Import
useSWRhook fromswr - Call
useSWRwith the API route andfetchas parameters datawill hold the response when it loadserrorwill be populated if fetch fails- You can show loading and error UI before data loads
The
fetchparam tellsuseSWRto automatically handle the request.Some benefits over regular
fetch:- Caching and deduplication
- Import
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.