Error with SWR hook: "Fetcher argument not supplied"

Using the SWR hook for the first time, everything is working smoothly so far. However, I've encountered an error that I can't seem to figure out. Let me share my code with you.

This is the global configuration:

<AuthContext>
    {isValidRoute && <Navbar />}
    <SWRConfig
        value={{
          fetcher: (url: string) => axios.get(url).then(res => res.data)
        }}
    >
        <Component {...pageProps} />
    </SWRConfig>
</AuthContext>

Here's how I'm using it:

import useSWR from "swr";

import { NavbarPart3 } from "../NavbarStyled";
import { dataObject } from "../../../GlobalInterfaces/AuthContextInterfaces";

const Part3 = () => {
  if (typeof window !== "undefined") {
    const userId: dataObject = JSON.parse(localStorage.getItem("Auth"));
    const { data } = useSWR(
      "http://localhost:5000/api/user/singleU/" + userId.user.id
    );
    console.log(data);
  }

  return <NavbarPart3></NavbarPart3>;
};

export default Part3;

Now, onto the ERROR:

Expected 4 arguments, but got 1.ts(2554)
use-swr.d.ts(4, 91): An argument for 'Fetcher' was not provided

The Challenge: My goal is to troubleshoot this issue. Any idea what might be causing the problem?

Answer №1

Summary: Make sure to wrap the component where you call useSWR with the SWRConfig provider that defines the global fetcher.


If you're using the Part3 component within your NavBar, the error might be due to how it's being called.

To fix this, move

{isValidRoute && <Navbar />}
inside the SWRConfig provider like shown below.

<AuthContext>
    <SWRConfig
        value={{
            fetcher: (url: string) => axios.get(url).then(res => res.data)
        }}
    >
        {isValidRoute && <Navbar />}
        <Component {...pageProps} />
    </SWRConfig>
</AuthContext>

Avoid conditionally calling useSWR to adhere to the Hooks Rules.

In the Part3 component, place the useSWR call at the top level and the localStorage call inside a useEffect as shown in the code snippet below.

const Part3 = () => {
    const [userId, setUserId] = useState()
    const { data } = useSWR(
        // Fetch URL based on valid userId
        () => "http://localhost:5000/api/user/singleU/" + userId.user.id
    );

    useEffect(() => {
        const auth = JSON.parse(localStorage.getItem("Auth"));
        setUserId(auth);
    }, []);

    console.log(data);

    return <NavbarPart3></NavbarPart3>;
};

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

Issue with Firebase authentication during registration for a React application

Every time I attempt to register locally, I encounter the following error: "auth/network-request-failed", message: "A network error (such as timeout, interrupted connection or unreachable host) has occurred."} After registration, I'm simply directin ...

Exporting a NextJS project as a module

Seeking some advice and recommendations here. My ideas and attempts will be shared at the end. I have a NextJS project where I aim to export the top-level component (the entry file) in order to use it as a preview on my dashboard. The NextJS project is q ...

What is the process for selecting dependencies in react native?

Expanding on this: Imagine I have a React Native project running on a specific version with various npm packages installed. Each npm package will have its own node_modules and build.gradle file. In what situations will the dependencies local to that packag ...

Struggling with CSRF token while making an axios post request to Django

Currently, I am facing an issue while using React + Django to make a post request via axios. The problem seems to be arising from csrf verification. Despite trying various solutions found online for similar issues, none of them seem to be effective in reso ...

The Tooltip from React's material-ui@next component fails to render adjacent to the element within the TableHead Cell

In my React project using versions 15.6.2 and 16, along with material-ui@next version 1.0.0-beta.12, I encountered an issue with the Tooltip component. When I use the <Tooltip> inside a table header, the tooltip displays in the top left corner of the ...

Implementing a provider in NextJS for a select few pages

Can I add a provider specifically for certain routes in my Next.js app, instead of applying it to the entire application? Check out my "pages" folder Here's my context file [server.jsx] import { createContext, useState } from 'react'; con ...

Utilize SWR in NextJS to efficiently manage API redirection duplication

When using SWR to fetch data, I encountered an error where the default path of nextjs was repeated: http://localhost:3000/127.0.0.1:8000/api/posts/get-five-post-popular?skip=0&limit=5 Here is my tsx code: 'use client' import useSWR from &quo ...

Struggling with this npm i problem?

I have tried multiple solutions, but I keep encountering an issue with npm install. I even deleted the package-lock file and attempted using the --force or --legacy-peer-deps option without success. npm WARN deprecated <a href="/cdn-cgi/l/email-protecti ...

Implement an event listener on the reference obtained from the React context

Within the React context provider, a ref is established to be utilized by another component for setting a blur event listener. The issue arises when the blur event fails to trigger the listener. The following is a snippet of code from the context provider ...

Tips for customizing the color of Menu in material-ui v5

I've been searching for solutions to change the background color of the Menu, but the methods I found are outdated. The use of @mui/styles and makeStyles is now deprecated, as stated in mui.com/styles/basics/#hook-api. I attempted to change the backgr ...

Can Enzyme snapshots be utilized with React fragments?

Are React fragments compatible with Enzyme's snapshots? Currently, it appears that fragments from React 16+ are being displayed as Symbols in enzyme's shallow() method, leading to a conversion error: "TypeError: Cannot convert a Symbol value to a ...

Retrieve the value stored in the theme using the useState hook

Currently in the process of developing a React NextJS application integrated with MaterialUI. I have a header component that contains a switch element intended to facilitate toggling between dark and light modes within my theme file (which is a separate en ...

Setting Default Values for Multi-select in React-select Async

What is the method for setting default selected values in React-select Async Multi-select? Below is a sample form utilizing react-hook-form and react-select: <form onSubmit={handleSubmit(onSubmit)} > {updateError && renderError(updateError)} ...

Error: Attempting to access property 'map' of an undefined value

I am currently working on setting up a unit test for the code snippet below. I have identified where the error is occurring: populateActionDropdown = (actionList) => { let actions = actionList.map(action => { if (action.Name != 'Sig ...

Ways to adjust the view of a React Vis.JS Network Graph: How to zoom in or out

Hey there, I've set up my Network Graph with the following configuration: const exceptionsGraph = { nodes: graph, edges: edges } // Graph Options const options = { height: "80%", width: "100%", node ...

What causes og:image to fail to render in React?

Having trouble with displaying a thumbnail when sending a website link in a Facebook message. I tried using s-yadav/react-meta-tags and followed a tutorial, but the image is not showing up after the link is sent. Link: I have applied the following code i ...

AlignItems not functioning properly within a list component in NativeBase

My attempt to align the Thumbnail to the topLeft using justifyContent: 'flex-start' is not working as expected. Here's my code snippet: <Content> <View key = {index} style={styles.commentBody}> <List> <ListItem ...

"Enhance user experience with Material UI's versatile layout component designed for seamless transition between desktop

I am designing a responsive Single Web App using material ui, but I'm unsure about whether to use a grid or a box for the main component placement. Here is a visual representation of how the main components are arranged in different screen sizes: md, ...

Encountered CSRF validation error while working with a Python Django backend in conjunction with React frontend using Axios for making POST requests

I recently completed a tutorial at and now I'm attempting to add a POST functionality to it. Despite obtaining the csrf from cookies and including it in the "csrfmiddlewaretoken" variable alongside a test message in json format for the axios function ...

I am experiencing an issue with the PUT method on my API as it is not correctly setting the req.body data

Below is the code snippet for implementing the PUT method: [/api/[id].ts] case "PUT": try { const user = await UserModel.findOneAndUpdate( { _id: id, }, { $set: req.body, ...