Did I incorrectly pass headers in SWR?

After taking a break from coding for some time, I'm back to help a friend with a website creation project. However, diving straight into the work, I've encountered an issue with SWR.

Challenge

The problem I'm facing is related to sending an Authorization: Bearer header. Whenever the page loads, SWR only displays its loading state. I suspect it's a simple issue but any assistance would be greatly appreciated. I have already checked the developer tools, but nothing related to SWR seems to be present.

The API Site is developed using Strapi V4, and I acknowledge that they have made changes to their API response structure, which might be causing an issue for me. However, I haven't identified one yet, so if you notice anything wrong, please inform me!

Code Snippet

import {
  Table,
  TableCaption,
  Thead,
  Tr,
  Th,
  Tbody,
  Td,
  Tfoot,
} from "@chakra-ui/react";
import useSWR from "swr";
import axios from "axios";

const fetcher = async (url) => {
    const res = await axios.get(url, {
      headers: {
        "Authorization": `Bearer ${process.env.API_KEY}`,
      },
    });
    return res.data;
  };

export const BluForTable = () => {
    const { data, error} = useSWR(
        ["https://api-skr.herokuapp.com/api/factions", fetcher]
    );

    if(error) return (
        console.log(error),
        (
            <div>Failed to load {error.message}</div>
        )
    )
    if(!data) return <div>loading...</div>
    
  return (
    <>
    <div>
      {data.map((faction) => (  
      <Text>
        {faction.data.attributes.Title}
      </Text>
      ))}
    </div>
    <Table variant="simple">
        <TableCaption>Imperial to metric conversion factors</TableCaption>
        <Thead>
          <Tr>
            <Th>To convert</Th>
            <Th>into</Th>
            <Th isNumeric>multiply by</Th>
          </Tr>
        </Thead>
        <Tbody>
          <Tr>
            <Td>inches</Td>
            <Td>millimetres (mm)</Td>
            <Td isNumeric>25.4</Td>
          </Tr>
          <Tr>
            <Td>feet</Td>
            <Td>centimetres (cm)</Td>
            <Td isNumeric>30.48</Td>
          </Tr>
          <Tr>
            <Td>yards</Td>
            <Td>metres (m)</Td>
            <Td isNumeric>0.91444</Td>
          </Tr>
        </Tbody>
        <Tfoot>
          <Tr>
            <Th>To convert</Th>
            <Th>into</Th>
            <Th isNumeric>multiply by</Th>
          </Tr>
        </Tfoot>
      </Table>
      </>
  );
};

API Response

{
    "data": [
        {
            "id": 1,
            "attributes": {
                "Title": "Russia",
                "faction_information": "# Russian Squad Faction\n",
                "faction_lunch_date": "2015-02-28",
                "createdAt": "2022-01-28T14:42:02.087Z",
                "updatedAt": "2022-01-28T14:46:02.807Z",
                "publishedAt": "2022-01-28T14:46:02.804Z",
                "media_link": null
            }
        },
        {
            "id": 2,
            "attributes": {
                "Title": "US",
                "faction_information": "# whatever",
                "faction_lunch_date": null,
                "createdAt": "2022-01-29T04:37:36.773Z",
                "updatedAt": "2022-01-29T04:38:23.549Z",
                "publishedAt": "2022-01-29T04:37:48.962Z",
                "media_link": null
            }
        }
    ],
    "meta": {
        "pagination": {
            "page": 1,
            "pageSize": 25,
            "pageCount": 1,
            "total": 2
        }
    }
}

Answer №1

There seems to be an issue with passing a key in your code snippet:

const { data, error} = useSWR(
        ["https://api-skr.herokuapp.com/api/factions", fetcher]
    );

The first argument for the useSWR function should be the key, while the second argument should be the fetcher. By placing them inside an array, useSWR interprets it as a composite key (usually used in advanced scenarios).

To fix this, simply remove the array brackets and pass the key and fetcher as separate arguments:

const { data, error} = useSWR(
        "https://api-skr.herokuapp.com/api/factions", fetcher
    );

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

Tips for retrieving return values from an ajax form submission

When using ajax to submit a form, I encountered an issue where the process would halt at api.php and not return to the ajax success. Below is the code snippet: <form method="POST" id="form_1" action="../api.php" enctype="multipart/form-data" novalidate ...

Incorporate unique images and titles into shared Facebook links on-the-fly using React JS and Next JS applications

I have been working on my React JS web application that features a dynamic list of articles. I am currently trying to implement a feature that allows users to share the current link, which is the article details page, on Facebook. Despite spending hours ...

Error in typescript: The property 'exact' is not found in the type 'IntrinsicAttributes & RouteProps'

While trying to set up private routing in Typescript, I encountered the following error. Can anyone provide assistance? Type '{ exact: true; render: (routerProps: RouterProps) => Element; }' is not compatible with type 'IntrinsicAttribu ...

Error encountered in my JavaScript file - Unexpected Token < found on line 1 of the loadash.js script

I am right at the end of creating a sample dashboard with charts using dc.js, but I have hit a roadblock with one error remaining. This error is causing an issue. Unexpected token < on line 1 for loadash.js. The loadash.js file is valid, but for som ...

How can you transfer array elements to a new array using JavaScript?

I have a task to transform the fields of an array received from one server so that they can be understood by another server for upload. My approach involves first retrieving and displaying the original field names from the initial server's array to al ...

Guide to initializing the state in pinia with Typescript

I am encountering an issue while trying to add typescript to a pinia store. Any suggestions on how to resolve this problem would be appreciated. The project currently utilizes pinia:^2.0.16 and Vue:3.2.37 The error message is as follows: Type '{}&a ...

Prevent anchor jumping caused by popstate event in Safari

This situation is really testing my patience. When navigating within the same page using anchors, the browser automatically takes you back/forward to the location of that link in your history when popstate is triggered. One might think that you could prev ...

Assign the filename to the corresponding label upon file upload

I've customized my file uploader input field by hiding it and using a styled label as the clickable element for uploading files. You can check out the implementation on this jsFiddle. To update the label text with the actual filename once a file is s ...

What is the best way to distinguish between enabled buttons using Protractor?

I am facing a challenge with a table containing 20 buttons. Half of these buttons are disabled while the other half is enabled. I am looking for a way to filter out the enabled buttons and click on each of them using a for loop. The buttons that I want to ...

Obtain a custom token after next authentication through Google login

Utilizing next js, next auth, and a custom backend (flask), I have set up an API Endpoint secured with jwt token. In my next js frontend, I aim to retrieve this jwt token using the useSession hook to send requests to these API Endpoints. Everything functio ...

Unable to locate the module '/workspace/mySQL/node_modules/faker/index.js'

Hi there, I'm currently facing an issue while trying to run the app.js file in my project through the terminal. It keeps showing me an error message that I am unable to resolve. To provide some context, I have already installed the faker package using ...

What is causing the behavior of this JavaScript code in the Execution Context?

I recently delved into the world of asynchronous programming in JavaScript and wanted to share some code for examination: const myPromise = () => Promise.resolve('Success!'); function firstFunction() { myPromise().then(res => console. ...

When I attempt to run several promises simultaneously with Promise.All, I encounter an error

My code contains a series of promises, but they are not being executed as expected. Although the sequence is correct and functional, I have found that I need to utilize Promise.all in order for it to work properly. dataObj[0].pushScreen.map(item => { ...

Angular fails to include the values of request headers in its requests

Using Django REST framework for the backend, I am attempting to authenticate requests in Angular by including a token in the request headers. However, Angular does not seem to be sending any header values. Despite trying various methods to add headers to ...

Tips for creating a function that utilizes a select option value

I'm struggling with a form that includes two select inputs. I want the second input to only be enabled if the first one has been selected. I attempted using an onclick event, but it didn't work out as expected. Can anyone provide assistance? (apo ...

Tips for activating text selection in PDF.js

Struggling to enable text selection in PDF.js after successfully displaying a PDF? Seeking a simple example to guide you through the process? Despite trying various approaches, I haven't achieved the desired outcome yet. My current code snippet is a ...

AngularJS - encountering a 404 error when reloading the page after removing the Hashbang

After taking out the hashbang from my routes by using $locationProvider.html5Mode(true); Now, when I go to a page like "domain.com/download", it works. But if I refresh this same page, I get a 404 Error. URLs like "domain.com/download" can only be acce ...

How to send the file path to an API in JavaScript to convert it

I am currently working on a web application that allows users to upload a wav file and convert it to mp3 format. I have successfully implemented the wav to mp3 conversion and saving it to the project folder. However, I am facing an issue with dynamically p ...

Utilizing local component files as packages in NPM: A comprehensive guide

Lately, I've been working on a substantial project using React along with react-router-dom. However, I recently started incorporating NextJS into the project and noticed that it lacks some features that are present in react-router-dom. To address this ...

Display the same data point on a Google Map from two different rows of a database

I'm looking to display multiple values for profFName and profLName on a map with just one point showing this information. If I have (2) pID connected to the same marker, I want it to show both profFName and profLName on a single point. Currently, it ...