9

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?

Waterfall
  • 584
  • 1
  • 5
  • 15

1 Answers1

25

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);
dileep nandanam
  • 2,827
  • 18
  • 20
  • 3
    How does the SWR know to pass the header key as "Authorization"? and, how do I pass the custom headers? – Ravi Teja Vupasi May 19 '21 at 12:08
  • SWR only consider [url, token] combination, you can decide the headers as you want. @RaviTejaVupasi – dileep nandanam May 21 '21 at 03:12
  • @RaviTejaVupasi, it doesn't. Keep in mind that an remote fetching comes from fetcher functions that are supplied by you, so you just configure it there. SWR hands the rest -- caching, mutation subscriptions, etc. The URL that is passed to the useSWR() hook just serves as a key that marks all data accessed that way as 'dirty' and worthy of revalidation (refetching). It is not telling SWR to fetch. That's up to the fetcher function. – Artemis Prime Nov 27 '22 at 16:33
  • In this version of the hook, the URL / key is passed to the fetcher, but that is just for convenience. One can just as well have the URL hard-coded in the fetcher and supply a key that is some other string. The purpose of the key is so that all other components that use it get updated when the data is mutated. – Artemis Prime Nov 27 '22 at 16:42
  • why the document does not describe like you?! They say useSWR(['/api/user', token], ([url, token]) => fetchWithToken(url, token)). Using this, in the fetcher function body, token is undefined – Behzad Jan 24 '23 at 04:51