I use SWR 2.2.5
within Next.js 14.2
to load data from my node.js
server. I need to send a header with access token for authorization to get the data back. The token comes from an AuthContext with which I wrap all of my application.
I’m able to add the header to the async fetch request but as soon as I try to get the currentUser
from the custom useAuth hook (uncomment const { currentUser } = useAuth()
) I don’t get an error but also I see that there is no request sent to the server.
Here is my code:
'use client'
import useSWR from "swr";
import { useAuth } from "@/contexts/AuthContext";
let headers = new Headers();
headers.append('Content-Type', 'application/json');
headers.append('Accept', 'application/json');
headers.append('GET', 'POST', 'OPTIONS');
headers.append('Access-Control-Allow-Origin', "*");
async function fetcher([url, token]) {
// const { currentUser } = useAuth();
// const idToken = currentUser ? await currentUser.getIdToken() : "unauthorized";
// token.append('authorization', idToken);
const response = await fetch(url, { headers: token })
const data = await response.json()
return data
}
const Page = () => {
const { data } = useSWR(
[process.env.NEXT_PUBLIC_SERVER_PATH + "test", headers],
fetcher
);
console.log("data:", data)
return <h1>{data && "do something with data here"}</h1>
};
export default Page;
Any help appreciated, thanks!