Xaarth
Xaarth

Reputation: 1151

useSWR - How to pass config object to fetch

I'm trying to integrate useSWR in a next js project I'm working on.

I want to pass a config to fetcher as an argument. I have read about Multiple Arguments in the docs

but it's not returning the data for some reason. it is making the api request I can see that in the network tab.

not sure how to do this.

any suggestions?

const fetcher = async (url, config) => {
  let res;

  if (config) {
    res = await fetch(url, config);
  } else {
    res = await fetch(url);
  }

  if (!res.ok) {
    const error = new Error('An error occurred while fetching the data.');

    error.info = await res.json();
    error.status = res.status;
    throw error;
  }

  return res.json();
};

const { data, error } = useSWR(
  [
    rolesUrl,
    {
      headers: {
        Authorization: `Bearer ${user.token}`,
        'Content-Type': 'application/json',
      },
    },
  ],
  fetcher
);

Upvotes: 1

Views: 5175

Answers (1)

Xaarth
Xaarth

Reputation: 1151

After a very long debuging I found out. fetch is getting the config object.

and then makes the request to the api. then useSWR returns the response. which causes the component to re-render. the config object gets recreated.

useSWR thinks argument updated and make the api request again. that's why we don't get the data.

I have fixed this with useMemo hook

const config = useMemo(
  () => ({
    headers: {
      Authorization: `Bearer ${user.token}`,
      'Content-Type': 'application/json',
    },
  }),
  [user.token]
);

const { data, error } = useSWR([rolesUrl, config], fetcher);

Upvotes: 5

Related Questions