I am trying to configure a global SWRConfig in my Next.js application. In my _app.js file, I have the following setup:
import '@/styles/bootstrap.min.css';
import "@/styles/globals.css";
import Layout from "@/components/Layout";
import { SWRConfig } from "swr";
export default function App({ Component, pageProps }) {
return (
<>
<Layout>
<SWRConfig value={{
fetcher: async (url) => {
const res = await fetch(url);
if (!res.ok) {
const error = new Error("An error occurred while fetching the data.");
error.info = await res.json();
error.status = res.status;
throw error;
}
return res.json();
},
}}
>
<Component {...pageProps} />
</SWRConfig>
</Layout>
</>
);
}
However, in Next.js version 13, my layout.js file in the app folder has a different structure:
import './globals.css';
import { Inter } from 'next/font/google';
import Navbar from '@/components/Navbar';
const inter = Inter({ subsets: ['latin'] });
export const metadata = {
title: 'Create Next App',
description: 'Generated by create next app',
};
export default function RootLayout({ children }) {
return (
<html lang="en">
<body className={inter.className}>
<Navbar /><br />{children}
</body>
</html>
);
}
I attempted to wrap the HTML part with
<SWRConfig>...</SWRCongig>
, but encountered errors. If I could set up a global fetcher using:
<SWRConfig value={{
fetcher: async (url) => {
const res = await fetch(url);
if (!res.ok) {
const error = new Error("An error occurred while fetching the data.");
error.info = await res.json();
error.status = res.status;
throw error;
}
return res.json();
},
}}
>
I would be able to avoid duplicating this code. Any assistance on how to achieve this is greatly appreciated.