5

I am switching certain CRUD functionality that I used to provide with a token, but now I am using SWR and I don't know how to convert it. I used this hook for GET methods but for others, I don't know what to do!

export default function useGetData(apiKey) {
const fetcher = async (...args) => await fetch(...args).then(res => res.json());
const { data, mutate, error } = useSWR(apiKey, fetcher);

const loading = !data && !error;

return {
    loading,
    user: data,
    mutate
}
}

1 Answers1

5

OK, I found the answer :

import useSWR from 'swr';
import { getTokenFromLocalStorage } from '../../services/storage';
  export default function useGetData({ url, payload, options = {}}) {
  const mainUrl = process.env.NEXT_PUBLIC_BASE_URL + URL;
  const method = payload ? 'POST' : 'GET';
  const fetcher = async () => {
    const headers = {
      Authorization: `Bearer ${getTokenFromLocalStorage()}`
    };
    const options = {
      method,
      headers,
      ...(payload && { body: payload }),
    };

    return await fetch(mainUrl, options).then((res) => res.json());
  };
  const defaultOptions = {
    revalidateIfStale: false,
    revalidateOnFocus: false,
    revalidateOnReconnect: false,
  };
  const { data, mutate, error, isValidating } = useSWR(url + method, fetcher, {
    ...defaultOptions,
    ...options,
  });
  const loading = !data && !error;
  return { data, loading, error, mutate, isValidating };
}