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