Caching API Responses with SWR
Use the SWR (stale-while-revalidate) hook to fetch and cache API responses, automatically revalidating data in the background.
import useSWR from 'swr';
function fetcher(url) {
return fetch(url).then(r => r.json());
}
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 JavaScript code uses the useSWR hook from the SWR library for data fetching. The fetcher function wraps the fetch API and parses the response as JSON. The UserProfile component takes a userId prop and uses useSWR to fetch the user's data from the API using the userId. The data is automatically cached and revalidated in the background. Conditional rendering is used to handle loading and error states.
.loading {
color: #999;
}
.error {
color: red;
}
CSS code to style the loading and error messages displayed by the UserProfile component. '.loading' styles the text colour for loading state, and '.error' for error state.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>SWR Caching Example</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div id="user-profile"></div>
<script src="https://unpkg.com/swr"></script>
<script type="module" src="UserProfile.js"></script>
</body>
</html>
HTML boilerplate code for the SWR example. It includes a link to the external stylesheet (styles.css) for styling and two script tags. The first script tag is for the SWR library loaded from a CDN, and the second script tag loads the UserProfile component as a module.