Waterfall
Waterfall

Reputation: 714

How to send headers using swr

I am trying to send headers using SWR and Axios but the headers are not being sent.

 const fetcher = (url) =>
    axios
      .get(url, { headers: { Authorization: "Bearer " + auth.token } })
      .then((res) => res.data);
  const { data, error } = useSWR(
    `http://localhost:8000/api/v1/users/get-avatar`,
    fetcher
  );
  if (error) console.log(error);
  if (data) console.log(data);

What is the correct way to send headers with SWR?

Upvotes: 16

Views: 26490

Answers (1)

dileep nandanam
dileep nandanam

Reputation: 2895

As per the docs https://swr.vercel.app/docs/arguments you should do

const fetcher = (url, token) =>
    axios
      .get(url, { headers: { Authorization: "Bearer " + token } })
      .then((res) => res.data);

const { data, error } = useSWR(
  [`http://localhost:8000/api/v1/users/get-avatar`, auth.token],
  fetcher
);
if (error) console.log(error);
if (data) console.log(data);

Upvotes: 30

Related Questions