Tips for correctly sending headers with SWR requests?

I've made the decision to transition the majority of my API functions to SWR because of its enhanced capabilities!

Issue at Hand

However, I'm encountering a major problem trying to pass headers properly into SWR. Despite consulting the documentation and other resources, I can't seem to get it right. My setup involves working with the Twitch API, Next.js, and NextAuth for managing tokens and sessions. Below, you'll find a link to my GitHub repository along with the code snippet I'm currently struggling with.

Note:

Although I console log any error returns, when I navigate to the /dash page, it displays failed to load without generating an error in the console.

GitHub Repository

import axios from "axios";
import Link from "next/link";
import {
  VStack,
  Heading,
  Divider,
  Text,
  Box,
  Badge,
  Center,
} from "@chakra-ui/react";
import { useSession } from "next-auth/react"
import useSWR from 'swr'

const fetcher = (url) => {
  const { data: session, status } = useSession()
  axios
    .get(url, { 
        headers: { 
          'Authorization': `Bearer ${session.accessToken}`,
          'Client-Id': `${process.env.TWITCH_CLIENT_ID}`
        }})
    .then((res) => res.data);
}
     
function Dash () {
  const { data, error } = useSWR(`https://api.twitch.tv/helix/streams/key?broadcaster_id=630124067`,fetcher)
  
  if (error) return (
    console.log(error),
    <div>Failed to load</div>
  )
  if (!data) return <div>loading...</div>

  return (
    <VStack>
      <Text>{data.user_name}</Text>
    </VStack>
  )
}

export default Dash

Answer №1

In summary: Utilize an array as the key parameter in the useSWR function to pass multiple arguments when interacting with the fetcher function.


Initially, remember that useSession should strictly be invoked at the highest level of a React component or another hook to adhere to the established Rules of Hooks.

Subsequently, ensure to relocate the useSession call within the Dash component. Following this move, you can conditionally invoke the fetcher based on the presence of the session, transmitting the accessToken through an array in the key parameter (referencing Conditional Fetching).

function Dash() {
    const { data: session } = useSession()

    const { data, error } = useSWR(
        session ? ['https://api.twitch.tv/helix/streams/key?broadcaster_id=630124067', session.accessToken] : null,
        fetcher
    )
  
    // Remaining code
}

Lastly, adjust your fetcher function slightly to accept the accessToken parameter. Additionally, ensure to include a return statement after the Axios call for correct data retrieval.

const fetcher = (url, accessToken) => {
    return axios
        .get(url, { 
            headers: { 
                'Authorization': `Bearer ${accessToken}`,
                'Client-Id': `${process.env.TWITCH_CLIENT_ID}`
            }
        })
        .then((res) => res.data);
}

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

Can a JavaScript callback be transmitted via JSON?

Is there a way to pass a callback function via JSON instead of using a function object? window.onpopstate = function(e) { var state = e.state; switch(state['method']) { case 'updateFields': updateFields(sta ...

Having trouble getting my JS/CSS code to work for a single image music play/pause button. Any suggestions on how to fix it?

I'm currently working on a project and trying to incorporate a music button into the navigation bar. The goal is for the song to play when clicked, and then pause when clicked again. However, I've encountered some issues with getting it to functi ...

Managing the synchronization of a time-consuming method in Angular using TypeScript

We are currently utilizing TypeScript and Angular 6 in our development project and have a service class that is injectable: @Injectable() export class ProductService { getAllProducts(): Observable<Product[]> { return this.http.get(' ...

Transferring information from Django to JavaScript

Is it possible to pass data from Django views to Django templates using variables? For example, if I have a list called 'listone', can I somehow transfer this data to a JavaScript list created in the view? Are there alternative methods for achiev ...

Can we streamline this jQuery code by utilizing .hasClass and .bind?

Can this code be simplified? Initially, when #griffyindor has the 'active' class, I want all other houses (slytherin, ravenclaw, and hufflepuff) to show. If at any point it loses the 'active' class upon clicking something else, I want ...

What is the reasoning behind certain libraries offering methods that perform identical tasks, but one in synchronous and the other in asynchronous context?

It's common for libraries to provide two methods that perform the same task, with one running asynchronously and the other synchronously. For example, unlink in fs/promises is similar to unlinkSync in fs; also, compare, compareSync, hash, and hashSyn ...

Acquire data from an HTML Element

I was provided with the following div that was already created for me: <div data-sudo-slider='{"slideCount":1, "moveCount":1, "customLink":"#slider-nav a", "continuous":true, "updateBefore":false, "effect":"sliceRevealDown", "auto":true, "speed":1 ...

jQuery fails to fetch information

I am currently working with a straightforward script as shown below: $(function() { var url = theme_directory + '/func/api.php'; $.get( url, function(data) { alert("Data Loaded: " + data); }); }); Here is the code for api ...

Issue: The module '[object Object]' could not be located

const express = require('express'); const app = express(); const jade = require('jade'); const path = require('path'); const server = require('http').createServer(app); const io = require('socket.io').liste ...

choosing a specific element with jQuery to be used for future purposes

I'm having some trouble with the following code snippet: var star = $("._container > favorite"); var symbol = $(star.parentNode.parentNode).attr("symbol"); var exchange = $(star.parentNode.parentNode).attr("exchange"); After running ...

Instructions for sending an email through a form while displaying a pop-up message

My Objective To create a functionality on my website where users can input their email addresses in a form and receive a validation popup indicating whether the email is valid or not. Background Information I am currently working on a website that allow ...

Selenium WebDriverJs has difficulty in setting up a new client for iOS devices

Struggling to make Selenium WebDriverJS work with the iOS browser, but unfortunately facing some issues. I followed the instructions on setting up the "iWebDriver" project as mentioned on the iPhoneDriver wiki page. The Python script worked fine, and even ...

New update: Adjusting the chart by using the slider to modify the date values on the x-axis

Update: I have made changes to the question, the issue with values not appearing on the x-axis has been resolved. Now, as the slider is moved, the data on the graph remains constant and I can see changing x values. I am currently working on incorporating ...

Issue with Internet Explorer 8 preventing the ability to dynamically create buttons

When attempting to dynamically create a button in Internet Explorer, there is an error whereas it works perfectly in Firefox. var deleteButton = document.createElement('input'); ratingSliderContainer.appendChild(deleteButton); deleteButton.set ...

Activate the audit command for the npm enterprise registry

I'd like to know how to activate the npm audit command in my npm enterprise registry. Whenever I attempt to run the npm audit command, I encounter the following error: { "error": { "code": "ENOAUDIT", "summary": "Your configured registry ( ...

Tips for utilizing a for loop within an array extracted from a jQuery element for automation

I am looking to streamline the process using a for loop for an array containing 10 image files in the parameters of initialPreview and initialPreviewConfig. My envisioned solution involves the following code snippet: for (i = 0; i < 11; i++) { "< ...

Tips for stopping special characters from being copied and pasted into a number field

My goal is to ensure that only numbers can be copied and pasted into the 'number field'. By preventing the copy and paste of characters like 'e', '+', '-', and '.', I can ensure that the number field only c ...

Importing Laravel select2 library is necessary for enhancing user experience and improving

I've been attempting to incorporate select2 into my project without success. Every time I try these two methods, I always receive an error saying $('#state').select2 is not a function. However, when I include select2 in a standard <scrip ...

VueJS - Building a Form Template Within a Modal Component

Struggling to include a template in a modal and unsure how to pass variables to the child template: Below is the main HTML for the application: <div id="example" class="container"> <button class="btn btn-primary" type="button" @cli ...

What is the best way to send a function along with personalized data?

Currently, I am working on a project using node.js with socket.io. I am looking for a way to have socket.on() use a unique callback function for each client that joins the server. Here is my current technique: I have created a simple JavaScript class whi ...