Blog>
Snippets

Fetching Data on the Client-side using SWR

Implement client-side data fetching with the SWR hook for built-in caching, revalidation, and error handling capabilities.
import useSWR from 'swr'

// Function to fetch data
const fetcher = (...args) => fetch(...args).then(res => res.json())

// React component which fetches the data
function UserProfile({ userId }) {
  const { data, error } = useSWR(`/api/user/${userId}`, fetcher)

  if (error) return <div>Failed to load user</div>
  if (!data) return <div>Loading...</div>

  // Render data
  return <div>Hello, {data.name}!</div>
}
This piece of code imports the useSWR hook from the 'swr' library and defines a React component called UserProfile. It receives a userId prop to fetch the user's data. The fetcher function is defined to fetch data from an API and return a promise that resolves with the result of parsing the API response as JSON. The useSWR hook is then used inside UserProfile to fetch user data from an API endpoint using the userId and the defined fetcher function. The hook's response includes the data and error objects. Depending on the state of the request, the component conditionally renders error messages, a loading state, or the user's data.