To use the useSWR
hook for data caching and revalidation with custom error handling in Next.js, you'll first need to install the swr
package if you haven't already:
bashnpm install swr
Then, you can use it in your Next.js application. Below is an example of how you can utilize useSWR
with custom error handling:
jsx// Import the necessary dependencies
import useSWR from 'swr';
// Define a custom fetcher function to handle data fetching
const fetcher = async (url) => {
const res = await fetch(url);
if (!res.ok) {
throw new Error('Failed to fetch data');
}
return res.json();
};
// Component using useSWR with custom error handling
const MyComponent = () => {
// Define the API endpoint you want to fetch data from
const apiUrl = '/api/data'; // Replace with your actual API endpoint
// Fetch data with useSWR hook
const { data, error } = useSWR(apiUrl, fetcher);
// Custom error handling
if (error) {
return <div>Error: {error.message}</div>;
}
// Render loading state while data is being fetched
if (!data) {
return <div>Loading...</div>;
}
// Render data once fetched successfully
return (
<div>
{data.map(item => (
<div key={item.id}>{item.name}</div>
))}
</div>
);
};
export default MyComponent;
In this example:
fetcher
function that handles data fetching. Inside this function, we use fetch
to make a request to the specified URL. If the response is not successful (!res.ok
), we throw an error.useSWR
hook in our component, passing the API endpoint URL and the fetcher
function as arguments. This hook handles data caching and revalidation for us.error
returned by useSWR
. If there's an error, we render an error message.!data
), we render a loading indicator.You can replace /api/data
with your actual API endpoint URL. Additionally, customize the error handling and loading states according to your application's needs.