Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send headers using swr

Tags:

reactjs

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?

like image 237
Waterfall Avatar asked Dec 06 '25 04:12

Waterfall


1 Answers

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);
like image 127
dileep nandanam Avatar answered Dec 12 '25 10:12

dileep nandanam



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!