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

What is the best way to incorporate additional properties while utilizing useSession in Next.js with TypeScript?

I've encountered an issue while trying to add new properties using useSession() in a TypeScript environment. Although it works on console.log, there is an error related to the type mismatch. The useSession() function typically returns name, email, an ...

"Encountered an Unspecified Variable Error in executing document

Every time I open my Chrome console, it keeps showing an error message saying "toggleOnlyRelatedPosts is not defined". The script I'm working on doesn't seem to be functioning properly. I've added so many variables that I now feel lost and o ...

Performing an AJAX request to a form within a CSS modal

Greetings from France, and please excuse any language errors in my English. I am currently coding in Symfony 3 and have an entity called "book" which can have different attributes (client, student, organizer, and/or speaker) based on the selected "type" a ...

Remove background image when input form field is in focus

I am currently experimenting with the following approach: $('input').on('click focusin', function() { $('.required').hide(); }); However, it appears that this logic is not functioning as intended. Here is an ...

The Angular template driven forms are flagging as invalid despite the regExp being a match

My input looks like this: <div class="form-group"> <label for="power">Hero Power</label> <input [(ngModel)]="model.powerNumber" name="powerNumber" type="text" class="form-control" pattern="^[0-9]+$"id= ...

refresh the localstorage array using vanilla JavaScript

I am attempting to remove an element from an array stored in local storage. I am using vanilla JavaScript within a Vue.js 3 component. Here is my array: ["96", "281", "287", "415", "650", "661", & ...

The user values in jQuery alert function are correct, but the saveorupdate function fails to save null values in the database table

While using the alert function in jQuery, the user input values are alerted correctly, but for some reason they are being stored as null in the database table. Can anyone help me identify what might be causing this issue or what I might be doing wrong? I& ...

A guide on obtaining the date format according to locale using Intl.DateTimeFormat within JavaScript

Can someone assist me in obtaining the standard date format (such as MM/DD/YYYY) based on a specified local id? The code snippet provided below is not returning the desired format. Any guidance on how to achieve this would be greatly appreciated. var da ...

JavaScript - Uncaught TypeError: type[totypeIndex] is not defined

After following a tutorial and successfully completing the project, I encountered a JavaScript error saying "Uncaught TypeError: totype[totypeIndex] is undefined". When I tried to log the type of totype[totypeIndex], it initially showed as String, but late ...

Storing various text inputs in a MySQL database

Could anyone please assist me with fixing an issue I'm having with inserting data into a database from the form provided below? Unfortunately, I am unable to get it to work as expected. Here is the complete form: <html> <head> <m ...

Encountering a hiccup during the installation process of Angular CLI

I'm encountering an issue in the command line, seeking assistance C:\Users\admin>npm -v 6.9.0 C:\Users\admin>npm install -g @angular/cli npm ERR! Unexpected end of JSON input while parsing near '...vkit/core":"8.0.4", ...

Ways to transform an Array into an object

I had the idea to create a personalized dictionary for customers by utilizing the reduce function. Currently, I am achieving this using the forEach method. const customers = [ { name: 'ZOHAIB', phoneNumber: '0300xxxxx', other: ' ...

What is the significance of AngularJS in crafting Single Page Applications?

My introduction to AngularJS was discovering its perfection for Single Page Applications (SPAs). I'm intrigued by what this means and eager to learn more about it. Can someone explain the significance of SPAs in relation to AngularJS? ...

Accessing Stencil through a corporate proxy network

As I embark on my inaugural Stencil project, I've encountered a puzzling error message: Cannot download "https://github.com/ionic-team/stencil- component-starter/archive/master .zip" Check your internet connection Error: connect ETIMEDOUT" De ...

Displaying information in form using ajax within the laravel framework

I am currently utilizing ajax to retrieve data from a database. While I am able to successfully retrieve the data on the backend, I am facing difficulties displaying it in the input field below. I have tried writing some code, but it seems that the JavaScr ...

When using NodeJS, having multiple 'if' statements may result in conflicting headers being returned,

Introduction to Promises. Encountering challenges in NodeJS due to the utilization of multiple if-statements and return-statements. Considering leveraging Promise as a potential solution. This snippet showcases an example: const express = require(' ...

Using string replacement for effective search finding: Unleashing the power of substring matching

I have a method that adds an anchor tag for each instance of @something. The anchor tag links to a specific sub URL. Check out the code: private createAnchors(text: string) { return text.replace(/(@[^ @]+)/ig, '<a href="/home/user/$1">$1& ...

Adjusting the height of the Sencha Touch container to accommodate its content

In Sencha Touch, I have a view that generates a popup box from the right when a button in the bottom toolbar is clicked: Ext.define('TheApp.view.PopupTablet',{ extend: 'Ext.form.Panel', xtype: 'popupbox', confi ...

Loading CSS files conditionally in Angular2's index.html

Currently, my index.html page features a dark theme: <base href="/"> <html> <head> <title>XXX</title> </head> <body> <link rel="stylesheet" type="text/css" href="assets/dark_room.css"> <my-app ...

In JavaScript, a variable's value can be assigned to another variable using the variable

I have a collection of predetermined variables. I dynamically assign a value to another variable, which ends up representing the name of one of the predefined variables. This allows me to easily determine which set variable to use on a particular section o ...