0

I am attempting to switch my api usage to use SWR as it provides much more customisation options that I could very well benefit from. How ever the api GET request need to pass through 2 headers 'Authorization':Bearer ${session.accessToken} and 'Client-Id': ${process.env.TWITCH_CLIENT_ID} And after doing some research I found a couple of ways on how to do this but they are not working. The code below is what I have but when the page attempts to render it shows the screenshot bellow

How do I fix this or better yet can anyone show the proper way to send headers while using swr?

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, token) => {
const { data: session, status } = useSession()
    axios
      .get(url, { 
        headers: { 
          Authorization: `Bearer ${session.accessToken}` + token }})
      .then((res) => res.data);
        }
     
function Dash () {
  const { data, error } = useSWR([` https://api.twitch.tv/helix/streams/key?broadcaster_id=630124067`, auth.token],fetcher)
  
  if(error) return <div>Error {data.error}</div>
  if(!data) return <div>loading...</div>

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

}


export default Dash

enter image description here

MatDoak
  • 132
  • 5
  • 17
  • 2
    Are you sure that your `token` exists in `auth.token`? If you've seen [this question](https://stackoverflow.com/questions/65862928/how-to-send-headers-using-swr) and you're trying to implement it, you should consider that using ```useSWR([`http://localhost:8000/api/v1/users/get-avatar`, auth.token], fetcher);``` works because the `token` exists in `auth.token` field (It is apparent from the question: `axios.get(url, { headers: { Authorization: "Bearer " + auth.token } })`) – fsefidabi Oct 22 '21 at 07:56
  • Yeah the token does not exist in `auth.token` the token is taking from NextAuth's session `{session.accessToken}` which returns a OAuth bearer token from Twitch to Authorize there api. So then how do I pass these headers into the request? any help would be legendary – MatDoak Oct 22 '21 at 12:23
  • 1
    I don't know the exact implementation, since I have not access to the exact same code and config to try it, but I hope [this link](https://github.com/vercel/swr/discussions/684#discussioncomment-94198) helps you. Check how he has passed `user` to get `token`. – fsefidabi Oct 22 '21 at 12:32
  • All good thanks for the help – MatDoak Oct 22 '21 at 12:45

0 Answers0