SWR Worldwide Settings

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.

Answer №1

<SWRConfig /> is a React Context-based component that should be placed within a React Client Component.

For detailed guidance on using React Context with the Next.js App Router, refer to the Next.js Documentation: https://nextjs.org/docs/getting-started/react-essentials#context


To implement this in your project, start by creating a new file called app/context/swr-provider.js:

// src/components/swr-provider.tsx
export const MySWRProvider = ({ children }) => (
  <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();
    },
  }}>
    {children}
  </SWRConfig>
);

Then, in your app/layout.js, import and use the <MySWRProvider /> component:

// app/layout.js
import './globals.css';
import { Inter } from 'next/font/google';
import Navbar from '@/components/Navbar';
const inter = Inter({ subsets: ['latin'] });

import { MySWRProvider } from './context/swr-provider.js'

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}>
        <MySWRProvider>
          <Navbar />
          <br />
          {children}
        </MySWRProvider>
      </body>
    </html>
  )
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Different techniques for retrieving elements generated by ng-repeat from their containing parent

Let's keep it simple - imagine we have a directive called headSlides. This directive's template includes an image that is being repeated using ng-repeat: <img class="bg" ng-repeat="image in images" ng-src="{{image.src}}"> I need to access ...

Exploring ways to capture all console outputs or retrieve the current console content in frontend development

Currently working with Angular and looking to integrate a bug reporting feature into my application. I want to capture the content of the browser's console for debugging purposes. However, I'm unsure of how to access it. Not all errors are logge ...

What is the best way to emphasize a link to the current page in vue.js?

I am working on a sidebar feature that displays several dynamically generated links (similar to creating notes and then linking to them): https://i.stack.imgur.com/1lxcy.png Users can add a new note by clicking the 'Add stage' button. The list ...

`Why TypeScript in React may throw an error when using a setter`

As I work on building a small todo app in TypeScript with React, I encountered an issue when attempting to add a new todo item to my list. It seems like the problem may lie in how I am using the setter function and that I need to incorporate Dispatch and s ...

An issue occurred: Unable to access properties from an undefined source

I'm facing an issue while working with webdatarocks and googlecharts in Next.js. Whenever I switch the pivot design to flat mode, I encounter an error when running the following code in my component: window.webdatarocks.googlecharts.getData( { ...

Problem with escaping special characters in random string HTML

As I was in the process of creating a JavaScript tool to generate random strings, with or without special characters, I stumbled upon an inspiring snippet that caught my attention: (): function randStr(len) { let s = ''; while (len--) s += ...

jQuery is consistently lagging one step behind when calculating the sum with keypress

I am currently working on developing a calculator that adds up the values entered with each key press. Here is the code snippet I have been using: $('#padd').keypress(function() { var ypoints = "200"; var points = parseInt( $(th ...

The webpage becomes unresponsive and gets stuck when sending a stream of requests to the web server via ajax

I am currently working on creating a signal on the webpage that displays either a green or red color based on values retrieved from a database. However, when I send a request after 10 seconds, the page appears to freeze and becomes unresponsive. I am strug ...

NextJs does not allow external synchronous scripts

I am currently working with Next.js version 11.x Whenever I attempt to add an external script like the example below, I encounter an error when executing the yarn build. <Head> <link rel="stylesheet" type=" ...

What could be causing the second switchMap to be triggered repeatedly upon subscription?

Check out the code snippet below for reproducing the issue: import { defer, BehaviorSubject, of } from "rxjs"; import { shareReplay, switchMap } from "rxjs/operators"; const oneRandomNumber = defer(() => of(Math.floor(Math.random() ...

How to incorporate user-submitted form data into the existing state using React

I am currently working on a React project that involves a form input. The goal is for the user to input a number into the field, and then take that number and add it to another number in the application's state. For example, if this.state.data initia ...

Avoid losing focus on href="#" (preventing the page from scrolling back up to the top)

Is there a way to prevent an empty href link from causing the page to scroll up when clicked? For example, if I have: <a href="#">Hello world</a> And this "Hello world" link is in the middle of the page. When clicked, the URL would look like ...

Retrieve the Query String Information from a Link and Generate a New Link in Another List

I am looking to extract information from a link in #list and then use that information to create a new link in #list3. The link I have is http://jsfiddle.net/4y5V6/24/. Is there a way to set it up so that when a link is clicked, it automatically gets added ...

Having issues with the $addToSet method in my MongoDB API implementation

Despite searching through various topics, I couldn't find a solution to my specific problem. In an effort to enhance my JavaScript skills, I embarked on creating a quote generator. I successfully developed the API and frontend components. However, c ...

Populate a dropdown menu using Javascript

[Code] $.ajax ({ 'method': 'GET', 'source': '/bpv-registratie/periods/show_period_list_by_year.html', 'charge': function () { }, 'finish': function (xmlHttp) { ...

Sorting data by percentages in AngularJS

I am currently facing an issue with sorting percentages in a table column. Despite using methods like parseFloat and other AngularJS (1.5.0) sorting techniques, the percentages are not being sorted as expected. [ {percentage: 8.82} {percentage: 0. ...

Utilizing AngularJS within a Captive Network Assistant (WISPr) on iOS and MacOS devices

In my past experiences with projects, it has been observed that Apple's Captive Network Assistant (also known as WISPr client) operates with a restricted browser. For further information, you can refer to How can I debug the browser in Captive Portal? ...

Learning React: Error - Unable to access the 'data' property when it is null

Currently, I am learning React by following a tutorial available at this link: http://facebook.github.io/react/docs/tutorial.html Specifically, I am focusing on the section related to fetching data from the server, which can be found here: http://facebook ...

How can I immediately disable a button upon clicking "cancel" on a modal that contains TextFields in React Version 18?

New to React development. Looking for a way to reset a button to its initial disabled state when canceling out of a modal. The scenario is that upon clicking a button, a dialog will appear with an "ADJUST" button that is initially disabled until text is ...

One can pass parameters to a promise's success callback within AngularJS using $q

I have encountered a situation that is similar to the one described in this post, but I am still unsure about how to implement it. I could use some assistance with setting up a successful callback. This is the current functioning code: function getStuff( ...